selenium模块:可以打开浏览器,然后像人一样去操作浏览器,程序员可以从selenium中直接提取网页的各个信息。
环境安装
1.pip install selenium
2.下载浏览器驱动:https://npm.taobao.org/mirrors/chromedriver
把解压缩的浏览器驱动chromedriver放在python解释器所在的文件夹
让selenium启动谷歌浏览器
from selenium.webdriver import Chrome
# 1.创建浏览器对象
web = Chrome()
# 2.打开网址
web.get("XXXXX")
selenium语法
1.找到某个元素,模拟点击元素的过程
el = web.find_element_by_xpath("XXXX")
el.click()
2.模拟在输入框,输入python,然后输入回车
from selenium.webdriver.common.keys import keys
web.find_element_by_xpath('XXXXX').send_keys("python",Keys.ENTER)
3.查找存放数据的位置,进行数据提取
li_list = web.find_elements_by_xpath("XXXXX")
for li in li_list:
name = li.find_element_by_tag_name("XXXXX").text
selenium窗口切换
el = web.find_element_by_xpath("XXXX")
el.click() #产生了新窗口
#在selenium视角中新窗口默认不切换
web.switch_to.window(web.window_handles[-1])
#关掉子窗口
web.close()
web.switch_to.window(web.window_handles[0])
#变更selenium的窗口视角,回到原来窗口中
处理iframe
处理iframe的话,必须先拿到iframe,然后切换视角到iframe,再然后才能拿到数据
iframe = web.find_element_by_xpath("XXXXX")
web.switch_to.frame(iframe)
web.switch_to.default_content() #切换回元页面
selenium处理下拉列表
from selenium.webdriver.support.select import Select
#定位到下拉列表
sel_el = web.find_element_by_xpath("XXX")
#对元素进行包装,包装成下拉菜单
sel = Select(sel_el)
#让浏览器进行调整选项
for i in range(len(sel.options)):
sel.select_by_index(i)
无头浏览器
无头浏览器是指使用selenium不自动弹出网页进行操作。
from selenium.webdriver.chrome.option import Options
opt = Options()
opt.add_argument("--headless")
opt.add_argument("--disable-gpu")
web = Chrome(options=opt)
selenium事件链处理图片验证码
from selenium.webdriver.common.cation_chains import ActionChains
ActionChains(web).move_to_element_with_offset(verify_img_element,x,y).click().perform()