1. 什么是Selenium
Selenium是一套完整的Web应用程序测试系统,它包含了测试的录制、编写及运行和测试的并行处理。支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。完全有JavaScript编写,因此可以运行于任何支持JavaScript的浏览器上。
2. Selenium爬虫优劣势分析
2.1 优势
不需要做复杂的抓包、构造请求、解析数据等,开发难度相对要低一些。其访问参数跟使用浏览器的正常用户一模一样,访问行为也相对更像正常用户,不容易被反爬虫策略命中。
在需要模拟用户登录、浏览器滑动或点击时,使用Selenium执行js语句非常容易实现,比较适合动态网页的信息爬取。
2.2 劣势
相比于抓包→构造请求→解析返回值的爬虫,由于Selenium需要生成一个浏览器环境,所有操作(与元素交互、获取元素内容等)均需要等待页面加载完毕后才可以继续进行,所以速度相比构造请求的慢很多。
如果是爬取静态网页,不建议使用Selenium,原因是速度太慢,效率太低。建议使用其他爬虫工具,比如Scrapy。
3. 安装Selenium模块及浏览器驱动配置
3.1 Windows系统安装Selenium
第一步:安装配置Python环境,并安装pip组件。
第二步:在命令行工具中执行如下命令
pip install selenium
第三步:检查是否安装成功,再次执行上面命令,出现如下图所示,表示成功。
3.2 Ubuntu系统安装Selenium
执行如下命令:
apt-get install python-selenium
注:如果提示安装其他组件,请根据提示进行安装。
3.3 配置浏览器驱动
第一步:查看支持的浏览器驱动,依次执行命令:
python
from selenium import webdriver
help(webdriver)
第二步:选择需要使用的浏览器驱动Webdriver,根据电脑的浏览器版本下载对应的驱动到本地。下面是常用驱动下载地址。
Chromedriver(谷歌浏览器) [下载地址](http://chromedriver.storage.googleapis.com/index.html)
Geckodriver(火狐浏览器) [下载地址](https://github.com/mozilla/geckodriver/releases)
IEdriver(IE浏览器) [下载地址](http://selenium-release.storage.googleapis.com/index.html)
Operadriver(*Opera*浏览器) [下载地址](https://cnpmjs.org/mirrors/operadriver)
第三步:将下载的驱动,拷贝到python安装目录。
4. Selenium爬虫框架
4.1 常用页面定位方法
# 获取单个页面元素
driver.find_element_by_xpath()
driver.find_element_by_id()
driver.find_element_by_name()
driver.find_element_by_class_name()
driver.find_element_by_link_text()
driver.find_element_by_tag_name()
# 获取多个页面元素
driver.find_elements_by_id()
driver.find_elements_by_class_name()
driver.find_elements_by_link_text()
driver.find_elements_by_name()
driver.find_elements_by_xpath()
driver.find_elements_by_tag_name()
4.1 基础框架
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
if __name__ == '__main__':
options = Options()
options.add_argument('--headless') # 不打开浏览器
options.add_argument('--disable-gpu') # 禁用GPU硬件加速
options.add_argument('user-agent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1"') # 添加访问头
# options.add_argument('proxy-server="60.13.42.109:9999"') # 添加代理
driver = webdriver.Chrome(options=options) # 使用驱动配置
driver.get("网站地址")
driver.implicitly_wait(10) # 等待时间
element = driver.find_element_by_xpath("//div[@class='para']") # 执行页面定位语句
isDisplayed = element.is_displayed() # 判断是否允许访问
print(isDisplayed)
print(element.text)
# 将滚动条移动到页面的顶部 0:为顶部;1000000:为底部
js = "var q=document.documentElement.scrollTop=10000000000" # js语句
driver.execute_script(js) # 执行语句
driver.close()
4.2 通用模板
执行文件main.java:
import time
import json
import urllib
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from resource import GetHeader
# 定义元素对象
class Item(object):
name = None
imgUrl = None
difficulty = None
pre_time = None
total_time = None
materials = []
class GetCookFood(object):
def __init__(self):
self.urlsFileName = "urlsFile.txt"
self.itemsFileName = "itemsFile.txt"
self.imageDir = 'images/'
self.GetItemsList()
def GetItemsList(self):
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument(GetHeader())
# options.add_argument('proxy-server="60.13.42.109:9999"') # 添加代理
driver = webdriver.Chrome(options=options)
items = []
itemsUrl = readFile(self.urlsFileName)
try:
driver.get("网站地址")
driver.implicitly_wait(10)
driver.find_element_by_name("phone_number").send_keys("1892462331311")
driver.find_element_by_name("password").send_keys("qwe223456711")
time.sleep(2)
driver.find_element_by_xpath('//button[@class="button--primary"]').click()
driver.refresh()
for index in range(0, len(itemsUrl)-1):
item = Item()
item.nutritions = []
try:
driver.get(itemsUrl[index])
driver.implicitly_wait(10)
item.name = driver.find_element_by_xpath('//h1[@class="recipe-card__title"]').text
item.imgUrl = driver.find_element_by_xpath('//img[@class="core-tile__image"]').get_attribute("srcset")
item.imgUrl = item.imgUrl.split('.jpg', 1)[0] + ".jpg"
item.difficulty = driver.find_element_by_id("rc-icon-difficulty-text").text.split("\n")[1]
item.pre_time = driver.find_element_by_id("rc-icon-active-time-text").text.split("\n")[1]
item.total_time = driver.find_element_by_id("rc-icon-total-time-text").text.split("\n")[1]
item.materials = driver.find_element_by_id("ingredients-0").text.split("\n")
print(item.name)
print("第"+str(index)+"个正在执行URL:"+itemsUrl[index])
items.append(item)
except Exception as e1:
print(e1)
items.append(item)
self.saveFile(self.itemsFileName, items)
except Exception as e:
print(e)
self.saveFile(self.itemsFileName, items)
return items
# 按行读取文件方法
def readFile(fileName):
itemsUrl = []
with open(fileName, 'r', encoding="utf-8")as fp:
while True:
line = fp.readline()
itemsUrl.append(line)
if not line:
break
fp.close()
return itemsUrl
# 保存文件
def saveFile(self, imageDir, saveFileName, fileList):
try:
with open(saveFileName, 'a', encoding="utf8")as fp:
for item in fileList:
line = json.dumps(self.obj_2_json(item), ensure_ascii=False) + "\n"
fp.write(line)
response = urllib.request.urlopen(item.imgUrl)
imageName = imageDir + item.name + '.jpg'
with open(imageName, 'ab')as fpImage:
fpImage.write(response.read())
fpImage.close()
fp.close()
print("保存完成")
except Exception as e:
print(e)
# 将文件存为json格式
def obj_2_json(self, obj):
return {
"name": obj.name,
"imgUrl": obj.imgUrl,
"difficulty": obj.difficulty,
"pre_time": obj.pre_time,
"total_time": obj.total_time,
"materials": obj.materials,
}
if __name__ == '__main__':
run = GetCookFood()
time.sleep(1000000)
请求头资源文件resource.java:
import random
USER_AGENT_LIST = [
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
"Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)"
]
def GetHeader():
header = 'user-agent=' + random.choice(USER_AGENT_LIST)
print(header)
return header
文档下载地址
https://wenku.baidu.com/view/1802f67b747f5acfa1c7aa00b52acfc789eb9f1b