# selenium自动化

先去谷歌浏览器下载对应内核的版本 (opens new window)

淘宝源 (opens new window)

然后把包放在python的同级目录下,这时候要注意了,先which python(python3) 找到目前执行的py路径,或者查看编译器设置项目的环境地址。

but我安装了selenium 没安装chromedriver也可以,莫非是因为selenium是4.6.0?找官网也没有说明,暂时不加了,等报错再说

python 安装 pip3 install selenium

这个地方我的mini装了好几个版本的py,自带2.7,user/bin里面有3.8,brew装了一个py3.10(opt/homebrew),which python3找到系统环境路径真实使用的python路径,然后编辑器设置一下对应的环境,只要和全局的对应起来,pip3安装东西的时候就不会找不到了。

下面正式开始。

# 反爬 你懂得。
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
})
1
2
3
4
options = webdriver.ChromeOptions()
options.add_argument("-headless") #无头模式
options.add_experimental_option('detach', True)  # 不自动关闭浏览器
driver = webdriver.Chrome(options=options)
1
2
3
4

高版本selenium都是执行完默认关闭浏览器了,要手动设置一下

我用的基本都是xpatch查找的,简单粗暴,只是selenium高版本没有直接by_xxx方法了,统一的find_element然后传参数

compath = '//*[@id="app"]/div/div[11]/div/div[3]/div'
showStockLabe = driver.find_element(By.XPATH, compath)
showStockLabe.text # 就是div上的文字

showStockLabe.click() # 点击按钮,但是有一些div莫名会出现问题,js绑定事件,可以用下一种方法
driver.execute_script("$(arguments[0]).click()", showStockLabe) # 点击按钮
1
2
3
4
5
6

# 提取和设置cookies

from selenium import webdriver
import json
dictCookies = driver.get_cookies()
jsonCookies = json.dumps(dictCookies)
print(jsonCookies)
with open('cookies.json','w') as f:
	f.write(jsonCookies)
print("cookie保存成功")

# 取

with open('cookies.json', 'r', encoding='utf-8') as f:
    listCookies = json.loads(f.read())

driver.get(url)
for cookie in listCookies:
    if 'expiry' in cookie:
        del cookie['expiry']
    driver.add_cookie(cookie)

driver.get(url)
driver.refresh()
time.sleep(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

这个地方,要先get一次url(因为默认打开域名是data;)然后不refresh大概率也可以。expiry这个字段看网站,基本是后端做token有效期验证,所以去不去效果都差不多

对于那种需要一直点击去请求的,可以手动接一下NoSuchElementException异常,防止崩溃,然后继续去点击,其他异常酌情处理

while True:
    for cbtnpath in colorA:  # 颜色数组
        for membtnPath in memoryA:
        	try:
        		xxxxx
        		pass
        	except NoSuchElementException:
                print("没有这个按钮")
                continue
1
2
3
4
5
6
7
8
9

最近浅写了几个python项目,已经爱上py了,简洁方便大气 ^_^