Selenium初步学习

使用Chrome浏览器
使用Selenium
然后从其中仿照人的思路进行爬取

页面切换逻辑

对于其中的窗口逻辑,由于selenium不会像正常浏览器一样,如果关掉的话会自动跳转到下一个页面,所以需要
使用switch_to来切换窗口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for li in li_list:
h3 = li.find_element_by_xpath("./div[1]/div[1]/div[1]/a/h3")
h3.click()
# 此时, 在浏览器这边. 我们看到的内容已经是详情页的内容了.
# 但是, 在selenium的眼中. 我们依然在首页.
# 所以, 必须得让selenium去调整它的视角
# 切换窗口
web.switch_to.window(web.window_handles[-1])
job_detail = web.find_element_by_xpath('//*[@id="job_detail"]/dd[2]/div')
txt = job_detail.text
print(txt)
time.sleep(1) # 节奏慢一点儿
# 关闭该窗口
web.close()
# 调整selenium的视角
web.switch_to.window(web.window_handles[0])

iframe的处理

同理 对于具有iframe类型的窗口,我们也需要通过switch_to来切换,从而切换到iframe中
例如

1
2
3
4
5
6
iframe = web.find_element_by_xpath("iframe的Xpath")
web.switch_to.frame(iframe)

# doo somehthing
# 然后跳出
web.switch_to.parent_frame()

下拉列表的处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from selenium.webdriver.support.ui import Select

web = Chorme
# 1. 定位下拉框元素并创建Select对象
dropdown = web.find_element_by_xpath('//*[@id="OptionDate"]')
sel = Select(dropdown)

print("Total options:", len(sel.options)) # 输出类似:所有的选项0123456
# 3. 遍历并选择每个选项
for i in range(len(sel.options)):
sel.select_by_index(i) # 根据索引位置切换选项
time.sleep(2) # 切换完了过后等待加载
# 此处可添加操作后等待或验证逻辑
# e.g.
table = web.find_element_by_xpath('//table[@id="your_table_id"]') # 假设表格ID
trs = table.find_elements_by_tag_name('tr') # 获取所有行
for tr in trs:
print(tr.text) # 打印每行文本内容

Tips

selenium 可以拿到页面渲染动态加载过后的代码,而不是页面源代码
request只能拿到页面源代码 而拿不到动态加载过后的

1
web.page_source()

无头浏览器

1
2
3
4
5
6
7
8
9
10
11
# 配置无头Chrome浏览器
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import Chrome

# 创建浏览器选项对象
opt = Options()
opt.add_argument("--headless") # 启用无头模式
opt.add_argument("--disable-gpu") # 禁用GPU加速

# 实例化Chrome浏览器(带配置选项)
web = Chrome(options=opt)

验证码识别

方案一

超级鹰平台
使用超级鹰的API就可以了 网站上直接下载源码示例即可
图片的提取使用

1
2
3
4
pic = web.find_element_by_xpath('xpath').screenshot/screenshot_as_base64 ...
pic_code = API
web.find_element_by_xpath().send_keys(pic_code)

方案二

图鉴平台。
https://pan.baidu.com/s/1YY0Z5K5BAlDztMcR5KgemQ

方案三 CV

javascript代码执行

selenium可以动态执行js

1
2
3
4
web.execute_script("""
var a = document.getElementsByClassName("un-login-banner")[0];
a.parentNode.removeChild(a);
""")