目录
1. Selenium 依赖及驱动安装
(1)python安装
pip install selenium
(2)浏览器driver安装
下载地址:
以chrome为例,解压压缩包,找到chromedriver.exe复制到chrome的安装目录(其实也可以随便放一个文件夹)。复制chromedriver.exe文件的路径并加入到电脑的环境变量中去。具体的:
进入环境变量编辑界面,添加到用户变量即可,双击PATH,将你的文件位置(C:\Program Files (x86)\Google\Chrome\Application\)添加到后面。
2. Selenium 常见操作
2.0 网址登录
from selenium import webdriver
# 实例化webdriver对象
browser = webdriver.Chrome()
# 请求页面
browser.get("http://baidu.com")
2.1 查找元素
在页面中寻找元素,一般分为 find_element_* , find_elements_*。其中 find_element_* 返回一个webelement对象,代表页面中匹配查询的第一个元素,find_elements_*返回对象列表,表示所有匹配的元素
查找元素一般通过以下几种方法都能锁定元素,在网页F12右击元素后 copy选项中选择
browser.find_element_by_xpath("") #根据xpath选择元素
browser.find_element_by_id("" ) # 根据元素id选择
browser.find_element_by_class_name("") #根据 class_name 选择元素
2.2 查找文本
在下拉框中选择指定的文本,场景如下图所示,框架结构为span标签中的文本
browser.find_element_by_xpath("//span[text()='AABS']").click() # 首先选中匹配文本的元素,然后点击
2.2 键盘及鼠标操作
1. send_keys输入自定义内容
usrname = browser.find_element_by_xpath(r'//*[@id="j_username"]')
usrname.send_keys('name')
2. click、double_click 单击、双击
from selenium.webdriver import ActionChains
browser.find_element_by_xpath("//*[@id='xxx']").click() # 单击
ActionChains(browser).double_click(name).perform() #双击并输入新的内容,可用于清空元素中原有文本
3. 常见问题
1. 无法定位元素
在选取元素时,常出现find方法及标签名字写对但是报错无法找到元素,报错
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id=" "]"}
原因是 该元素定位写在frame里,需要先切入frame,找到元素并操作后,再切出
browser.switch_to.frame(browser.find_element_by_xpath("//*[@id='main_content']")) # 切到frame
browser.find_element_by_xpath(r'//*[@id="index-"]').click() #选择元素并操作
browser.switch_to.default_content() #切出至默认frame
2. 爬取网页无数据的情况
如果爬取多条网页出现偶尔几条无数据的情况,可能是未加载出来,可用sleep设置,等待数据加载
import time
time.sleep(2)