selenium是Python的一个第三方库,对外提供的接口可以操作浏览器,然后让浏览器完成自动化的操作。
selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题
selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等,来拿到网页渲染之后的结果,可支持多种浏览器
1 下载驱动
http://npm.taobao.org/mirrors/chromedriver/2.35/
mac 系统:将解压后的chromedriver移动到/usr/local/bin目录下
windows系统:将解压后的chromdriver.exe放到python安装路径的scripts目录中即可,注意最新版本是2.38,并非2.9
2 安装pip包
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple selenium
Selenium支持非常多的浏览器,如Chrome、Firefox、Edge等,还有Android、BlackBerry等手机端的浏览器。另外,也支持无界面浏览器PhantomJS。
from selenium import webdriver
browser = webdriver.Chrome()
browser = webdriver.Firefox()
browser = webdriver.Edge()
browser = webdriver.PhantomJS()
browser = webdriver.Safari()
selenium3默认支持的webdriver是Firfox,而Firefox需要安装geckodriver 下载链接
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
search = driver.find_element_by_id("kw")
search.send_keys("美女")
search.send_keys(Keys.ENTER)
time.sleep(3)
driver.close()
webdriver提供了一系列的元素定位方法,常用的有以下几种:
分别对应python webdriver中的方法为:
find_element_by_id()
find_element_by_name()
find_element_by_class_name()
find_element_by_tag_name()
find_element_by_link_text()
find_element_by_partial_link_text()
find_element_by_xpath()
find_element_by_css_selector()
selenium提供了选择节点的方法,返回的是WebElement类型,那么它也有相关的方法和属性来直接提取节点信息,如属性、文本等。这样的话,我们就可以不用通过解析源代码来提取信息了,非常方便。
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('https://www.amazon.cn/')
tag = driver.find_element(By.CSS_SELECTOR, '#cc-lm-tcgShowImgContainer img')
print(tag.get_attribute('src')) # https://images-cn.ssl-images-amazon.com/images/G/28/kindle/design/2019/190218_ATF1500x300_moonshine_kindle._CB456708368_.jpg
#获取标签位置,名称,大小(了解)
print(tag.location) # {'x': -242, 'y': 149}
print(tag.tag_name) # img
print(tag.size) # {'height': 300, 'width': 1500}
Selenium可以驱动浏览器来执行一些操作,也就是说可以让浏览器模拟执行一些动作。比较常见的用法有:输入文字时用send_keys()方法,清空文字时用clear()方法,点击按钮时用click()方法。示例如下:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome()
driver.get("https://www.jd.com/")
input = driver.find_element_by_id('key')
input.send_keys("MAC")
time.sleep(2)
input.clear()
input.send_keys('python')
time.sleep(2)
input.send_keys(Keys.ENTER)
time.sleep(5)
driver.close()
在上面的实例中,一些交互动作都是针对某个节点执行的。比如,对于输入框,我们就调用它的输入文字和清空文字方法;对于按钮,就调用它的点击方法。其实,还有另外一些操作,它们没有特定的执行对象,比如鼠标拖拽、键盘按键等,这些动作用另一种方式来执行,那就就是动作链。
比如,现在实现一个节点的拖拽操作,将某个节点从一处拖拽到另外一处,可以这样实现:
from selenium import webdriver
from selenium.webdriver import ActionChains
import time
driver = webdriver.Chrome()
driver.get("http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable")
driver.switch_to.frame('iframeResult')
source = driver.find_element_by_css_selector('#draggable')
target = driver.find_element_by_css_selector('#droppable')
actions = ActionChains(driver)
actions.click_and_hold(source).perform()
time.sleep(2)
actions.move_to_element(target).perform()
time.sleep(3)
actions.move_by_offset(xoffset=50, yoffset=0).perform()
actions.release()
对于某些操作,Selenium API并没有提供。比如,下拉进度条,它可以直接模拟运行JavaScript,此时使用execute_script()方法即可实现。
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('https://www.jd.com/')
time.sleep(2)
driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')
time.sleep(3)
driver.execute_script('alert("123")')
time.sleep(2)
driver.close()
在selenium中,get()方法会在网页框架加载结束后结束执行,此时如果获取page_source,可能并不是浏览器完全加载完成的页面,如果某些页面有有额外的Ajax请求,我们在网页源代码中也不一定能成功获取到。所以,这里需要延时等待一定时间,确保节点已经加载出来。这里等待的方式有两种:一种是隐式等待,一种是显式等待。
1 隐式等待
当使用隐式等待执行测试的时候,如果selenium没有在DOM中找到节点,将继续等待,超出设定时间后,则抛出找不到节点的异常。换句话说,当查找节点而节点并没有立即出现的时候,隐式等待将等待一段时间再查找DOM,默认的时间是0。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get("https://www.baidu.com/")
input_tag = driver.find_element_by_id('kw')
input_tag.send_keys('美女')
input_tag.send_keys(Keys.ENTER)
contents = driver.find_element_by_id('content_left') # 没有等待环节而直接查找,找不到则会报错
print(contents)
driver.close()
2 显示等待
隐式等待的效果其实并没有那么好,因为我们只规定了一个固定时间,而页面的加载时间会受到网络条件的影响。这里还有一种更合适的显式等待方法,它指定要查找的节点,然后指定一个最长等待时间。如果在规定时间内加载出来了这个节点,就返回查找的节点;如果到了规定时间依然没有加载出该节点,则抛出超时异常。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
input_tag = driver.find_element_by_id('kw')
input_tag.send_keys('美女')
input_tag.send_keys(Keys.ENTER)
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_all_elements_located((By.ID, 'content_left')))
contents = driver.find_element(By.CSS_SELECTOR, '#content_left')
print(contents)
driver.close()
关于等待条件,其实还有很多,比如判断标题内容,判断某个节点内是否出现了某文字等。more
使用Selenium,还可以方便地对Cookies进行操作,例如获取、添加、删除Cookies等。
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.zhihu.com/explore')
print(driver.get_cookies())
driver.add_cookie({'name': 'name', 'value': 'germey'})
print(driver.get_cookies())
driver.delete_all_cookies()
print(driver.get_cookies()) # []
from selenium import webdriver
from selenium.common.exceptions import TimeoutException,NoSuchElementException,NoSuchFrameException
try:
browser=webdriver.Chrome()
browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
browser.switch_to.frame('iframssseResult')
except TimeoutException as e:
print(e)
except NoSuchFrameException as e:
print(e)
finally:
browser.close()
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait # 等待元素加载的
from selenium.webdriver.common.action_chains import ActionChains #拖拽
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.by import By
from PIL import Image
import requests
import re
import random
from io import BytesIO
import time
def merge_image(image_file,location_list):
"""
拼接图片
"""
im = Image.open(image_file)
im.save('code.jpg')
new_im = Image.new('RGB',(260,116))
# 把无序的图片 切成52张小图片
im_list_upper = []
im_list_down = []
# print(location_list)
for location in location_list:
# print(location['y'])
if location['y'] == -58: # 上半边
im_list_upper.append(im.crop((abs(location['x']),58,abs(location['x'])+10,116)))
if location['y'] == 0: # 下半边
im_list_down.append(im.crop((abs(location['x']),0,abs(location['x'])+10,58)))
x\_offset = 0
for im in im\_list\_upper:
new\_im.paste(im,(x\_offset,0)) # 把小图片放到 新的空白图片上
x\_offset += im.size\[0\]
x\_offset = 0
for im in im\_list\_down:
new\_im.paste(im,(x\_offset,58))
x\_offset += im.size\[0\]
#new\_im.show()
return new\_im
def get_image(driver,div_path):
'''
下载无序的图片 然后进行拼接 获得完整的图片
:param driver:
:param div_path:
:return:
'''
background_images = driver.find_elements_by_xpath(div_path)
location_list = []
for background_image in background_images:
location = {}
result = re.findall('background-image: url\("(.*?)"\); background-position: (.*?)px (.*?)px;',background_image.get_attribute('style'))
# print(result)
location['x'] = int(result[0][1])
location['y'] = int(result[0][2])
image\_url = result\[0\]\[0\]
location\_list.append(location)
image\_url = image\_url.replace('webp','jpg')
# '替换url http://static.geetest.com/pictures/gt/579066de6/579066de6.webp'
image\_result = requests.get(image\_url).content
image\_file = BytesIO(image\_result) # 是一张无序的图片
image = merge\_image(image\_file,location\_list)
return image
def get_track(distance):
# 初速度
v=0
# 单位时间为0.2s来统计轨迹,轨迹即0.2内的位移
t=0.2
# 位移/轨迹列表,列表内的一个元素代表0.2s的位移
tracks=\[\]
tracks\_back=\[\]
# 当前的位移
current=0
# 到达mid值开始减速
mid=distance \* 7/8
print("distance",distance)
global random\_int
random\_int=8
distance += random\_int # 先滑过一点,最后再反着滑动回来
while current < distance:
if current < mid:
# 加速度越小,单位时间的位移越小,模拟的轨迹就越多越详细
a = random.randint(2,5) # 加速运动
else:
a = -random.randint(2,5) # 减速运动
# 初速度
v0 = v
# 0.2秒时间内的位移
s = v0\*t+0.5\*a\*(t\*\*2)
# 当前的位置
current += s
# 添加到轨迹列表
if round(s)>0:
tracks.append(round(s))
else:
tracks\_back.append(round(s))
# 速度已经达到v,该速度作为下次的初速度
v= v0+a\*t
print("tracks:",tracks)
print("tracks\_back:",tracks\_back)
print("current:",current)
# 反着滑动到大概准确位置
tracks\_back.append(distance-current)
tracks\_back.extend(\[-2,-5,-8,\])
return tracks,tracks\_back
def get_distance(image1,image2):
'''
拿到滑动验证码需要移动的距离
:param image1:没有缺口的图片对象
:param image2:带缺口的图片对象
:return:需要移动的距离
'''
# print('size', image1.size)
threshold = 50
for i in range(0,image1.size\[0\]): #
for j in range(0,image1.size\[1\]): #
pixel1 = image1.getpixel((i,j))
pixel2 = image2.getpixel((i,j))
res\_R = abs(pixel1\[0\]-pixel2\[0\]) # 计算RGB差
res\_G = abs(pixel1\[1\] - pixel2\[1\]) # 计算RGB差
res\_B = abs(pixel1\[2\] - pixel2\[2\]) # 计算RGB差
if res\_R > threshold and res\_G > threshold and res\_B > threshold:
return i # 需要移动的距离
def main_check_code(driver,element):
"""
拖动识别验证码
:param driver:
:param element:
:return:
"""
login\_btn = driver.find\_element\_by\_class\_name('js-login')
login\_btn.click()
element = WebDriverWait(driver, 30, 0.5).until(EC.element\_to\_be\_clickable((By.CLASS\_NAME, 'gt\_guide\_tip')))
slide\_btn = driver.find\_element\_by\_class\_name('gt\_guide\_tip')
slide\_btn.click()
image1 = get\_image(driver, '//div\[@class="gt\_cut\_bg gt\_show"\]/div')
image2 = get\_image(driver, '//div\[@class="gt\_cut\_fullbg gt\_show"\]/div')
# 图片上 缺口的位置的x坐标
# 2 对比两张图片的所有RBG像素点,得到不一样像素点的x值,即要移动的距离
l = get\_distance(image1, image2)
print('l=',l)
# 3 获得移动轨迹
track\_list = get\_track(l)
print('第一步,点击滑动按钮')
element = WebDriverWait(driver, 30, 0.5).until(EC.element\_to\_be\_clickable((By.CLASS\_NAME, 'gt\_slider\_knob')))
ActionChains(driver).click\_and\_hold(on\_element=element).perform() # 点击鼠标左键,按住不放
import time
time.sleep(0.4)
print('第二步,拖动元素')
for track in track\_list\[0\]:
ActionChains(driver).move\_by\_offset(xoffset=track, yoffset=0).perform() # 鼠标移动到距离当前位置(x,y)
#time.sleep(0.4)
for track in track\_list\[1\]:
ActionChains(driver).move\_by\_offset(xoffset=track, yoffset=0).perform() # 鼠标移动到距离当前位置(x,y)
time.sleep(0.1)
import time
time.sleep(0.6)
# ActionChains(driver).move\_by\_offset(xoffset=2, yoffset=0).perform() # 鼠标移动到距离当前位置(x,y)
# ActionChains(driver).move\_by\_offset(xoffset=8, yoffset=0).perform() # 鼠标移动到距离当前位置(x,y)
# ActionChains(driver).move\_by\_offset(xoffset=2, yoffset=0).perform() # 鼠标移动到距离当前位置(x,y)
print('第三步,释放鼠标')
ActionChains(driver).release(on\_element=element).perform()
time.sleep(1)
def main_check_slider(driver):
"""
检查滑动按钮是否加载
:param driver:
:return:
"""
while True:
try :
driver.get('https://www.huxiu.com/')
element = WebDriverWait(driver, 30, 0.5).until(EC.element_to_be_clickable((By.CLASS_NAME, 'js-login')))
if element:
return element
except TimeoutException as e:
print('超时错误,继续')
time.sleep(5)
if __name__ == '__main__':
try:
count = 3 # 最多识别3次
driver = webdriver.Chrome()
while count > 0:
# 等待滑动按钮加载完成
element = main\_check\_slider(driver)
main\_check\_code(driver,element)
try:
success\_element = (By.CSS\_SELECTOR, '.gt\_success')
# 得到成功标志
success\_images = WebDriverWait(driver,3).until(EC.presence\_of\_element\_located(success\_element))
if success\_images:
print('成功识别!!!!!!')
count = 0
import sys
sys.exit()
except Exception as e:
print('识别错误,继续')
count -= 1
time.sleep(1)
else:
print('too many attempt check code ')
exit('退出程序')
finally:
driver.close()
破解滑动验证
手机扫一扫
移动阅读更方便
你可能感兴趣的文章