0x01 简介
之前写过一篇用python+selenium模块和PhantomJS模拟浏览器进行爬虫爬取的文章,今天又要用到的时候发现selenium模块已经不支持PhantomJS了,使用的时候会报错。要求换用Firefox或者Chrome进行爬取。本文决定采用Chrome浏览器进行实验。
0x02 环境搭建
1.selenium模块
python模块通过pip安装即可
python -m pip install selenium
2.Chrome浏览器
要模拟浏览器要求本地需要安装Chrome浏览器,官网下载对应版本即可,本次采用 71.0.3578.98(正式版本) (64 位)
3.chromedriver驱动
要调用Chrome浏览器需要安装Chromedriver驱动,且根据安装的浏览器的版本的不同需要安装不同的驱动版本。版本号对应如下:
chromedriver版本 支持的Chrome版本
v2.32 v59-61
v2.31 v58-60
v2.30 v58-60
v2.29 v56-58
v2.28 v55-57
v2.27 v54-56
v2.26 v53-55
v2.25 v53-55
v2.24 v52-54
v2.23 v51-53
v2.22 v49-52
v2.21 v46-50
v2.20 v43-48
本文使用的下载链接:链接:https://pan.baidu.com/s/18XXVmGJ4M-uUrbgphIvv9Q 提取码:t3vh
下载完成后,将解压出的exe文件拷贝至Chrome安装目录下,同时拷贝到python以及 python/scripts 目录下。
4.测试
以上部署完成通过以下用例进行测试,如果浏览器成功打开百度则成功。如果只运行浏览器没有打开百度,则证明驱动与浏览器版本不匹配,需要重新下载驱动。
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
0x03 selenium用法及参数
1.可以通过引入ChromeOptions模块对Chrome进行配置,常用的配置如下
from selenium import webdriver
driver_options = webdriver.ChromeOptions()
driver_options.add_arguments('lang=zh_CN.UTF-8') #设置编码格式为utf8
driver_options.add_arguments('--headless') #设置浏览器为无头模式
driver = webdriver.Chrome(chrome_options=driver_options)
通过设置浏览器为无头模式,在代码运行的过程中将不会弹出浏览器窗口,这样可以加快爬取时间,也使得爬取更隐蔽。
Chrome其他配置可以参考 https://blog.csdn.net/zwq912318834/article/details/78933910
0x04 模拟浏览器示例
通过以上配置就可以进行模拟浏览器的登录了,在此以qq邮箱的登录界面为例
from selenium import webdriver
#from selenium.webdriver.chrome.options import Options
import time
#import selenium.webdriver.support.ui as ui
def setup_driver():
driver_options = webdriver.ChromeOptions()
driver_options.add_argument('--headless')
driver_options.add_argument('lang=zh_CN.UTF-8')
driver = webdriver.Chrome(chrome_options=driver_options)
return driver
def get_html(driver):
driver.get('http://mail.qq.com')
driver.save_screenshot('test.png')
while True:
try:
#login = driver.find_element_by_xpath("//*[@id='qlogin_list']/a[1]")
driver.switch_to_frame('login_frame')
login = driver.find_element_by_xpath("//*[@id='qlogin_list']/a[1]")
print('sucess')
login.click()
break
except:
print('failed')
time.sleep(10)
driver.save_screenshot('test2.png')
def main():
driver = setup_driver()
get_html(driver)
if __name__ == '__main__':
main()
#//*[@id="img_out_582655512"]
#//*[@id="qlogin_list"]/a[1]
在编写过程中可能遇到的问题:
1.定位元素位置的过程中可能遇到找不到元素的错误
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:
这可能由于两个原因导致,首先是由于页面还没有完全加载出来后续代码就已经运行,所以找不到元素。这种情况可以用while+try的方式,如上代码所示。
其次还有可能是因为要寻找的元素放在 iframe 或者 frame 框架中,在iframe或者frame框架中的元素相当于一个新的界面,selenium会找不到其中的元素,解决方案是需要先让selenium定位到frame中再进行筛选。
driver.switch_to_frame('login_frame') #参数为name元素或者id元素
2.xpath语法问题
虽然可以通过 get_element_by_id 或者 get_element_by_class_name等参数进行定位,但是一个复杂的页面往往有许多的id和name很难定位,这时需要用到xpath进行定位。关于xpath的语法可以参考 http://www.w3school.com.cn/xpath/index.asp
还有另外一种简洁的导出xpath的方式,可以进入Chrome浏览器的审查元素界面,找到要定位的元素然后右键
Copy -> Copy XPath
如下所示
我爱Chrome。