数据采集——爬虫篇(三):selenium+Chrome实现自动化测试—爬取数据
.
1.selenium环境安装部署
首先安装Chrome谷歌浏览器
查看设置系统版本:
然后下载Chrome对应的webdriver
地址:http://npm.taobao.org/mirrors/chromedriver/
选择对应版本,我的版本是83.0.4103.97:
注:基本没有完全对应的版本,选择与当前版本最接近的即可
根据操作系统不同,选择对应驱动(选择为Windows):
下载解压并复制到chrome浏览器的安装路径Google/Chrome/Application下
复制当前路径,右击我的电脑打开属性,选择高级系统设置,再次选择环境变量,选择path变量,添加我们复制的application路径,之后全部点击确定,确保环境变量能够保存
之后打开dos命令,使用pip安装selenium库:
pip install selenium
等待安装完成,环境准备已经完成。
**
2.使用selenium
**
selenium编写
from selenium import webdriver #导入模块
Google = webdriver.Chrome() #导入谷歌浏览器,使用Google变量调用
编写采集步骤
(1)跳转到指定采集网站:
Google.get('https://www.baidu.com')
如下:
(2)接下来使用selenium的xpath定位来做一个简单的网页查找:
1.输入关键词:
Google.find_element_by_xpath('//*[@id="kw"]').send_keys('Britain_King csdn')
#find_element_by_xpath:寻找定位xpath位置,send_keys:输入关键词
如图:
2.点击搜索,寻找指定xpath完成点击操作:
Google.find_element_by_xpath('//*[@id="su"]').click()
#click点击操作
如图:
3.寻找第一个标签页点击跳转:
Google.find_element_by_xpath('//*[@id="1"]/h3/a').click()
#点击第一个标签页的xpath
如图:
成功完成练习案例。
代码总结如下:
from selenium import webdriver #导入模块
import time #导入时间模块
Google = webdriver.Chrome()
Google.get('https://www.baidu.com')
Google.find_element_by_xpath('//*[@id="kw"]').send_keys('Britain_Kingcsdn') #给指定位置传递参数
time.sleep(2) #延时2s方便页面加载
Google.find_element_by_xpath('//*[@id="su"]').click() #点击指定xpath
time.sleep(2) #延时2s方便页面加载
Google.find_element_by_xpath('//*[@id="1"]/h3/a').click() #点击指定xpath
.
.
.
.
**
3. 使用selenium简单数据采集博客文章标题:
**
代码如下:
from selenium import webdriver #导入模块
import time #导入时间模块
Google = webdriver.Chrome()
Google.get('https://www.baidu.com')
Google.find_element_by_xpath('//*[@id="kw"]').send_keys('Britain_Kingcsdn') #给指定位置传递参数
time.sleep(2) #延时2s方便页面加载
Google.find_element_by_xpath('//*[@id="su"]').click() #点击指定xpath
time.sleep(2) #延时2s方便页面加载
Google.find_element_by_xpath('//*[@id="1"]/h3/a').click() #点击指定xpath
time.sleep(2) #延时2s方便页面加载
Google.switch_to.window(Google.window_handles[-1]) #切换到当前最新标签页
for i in range(1, 6): #for 循环爬取标签页
title = Google.find_element_by_xpath('/html/body/div[6]/main/div[2]/div[2]/div['+str(i)+']/h4/a').text #根据xpath变化规律,div/article直接随文章变化,用for循环替换。
print(title)
结果如下: