环境
python 3
selenium
request
Selenium 是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。这个工具的主要功能包括:测试与浏览器的兼容性——测试你的应用程序看是否能够很好得工作在不同浏览器和操作系统之上。测试系统功能——创建回归测试检验软件功能和用户需求。支持自动录制动作和自动生成 .Net、Java、Perl等不同语言的测试脚本。
Requests 继承了urllib2的所有特性。Requests支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。
导入依赖库
from selenium import webdriver
from selenium.webdriver import ActionChains
from requests.cookies import RequestsCookieJar
import requests
设置请求头
from selenium import webdriver
from selenium.webdriver import ActionChains
from requests.cookies import RequestsCookieJar
import requests
运用seleium时不打开浏览器,直接后台爬取数据
#不打开浏览器
chrom_options=webdriver.ChromeOptions()
chrom_options.add_argument('--headless')
chrom_options.add_argument('--disable-gpu')
browser = webdriver.Chrome(chrome_options=chrom_options)
获取cookieJar来存放cookie
jar=RequestsCookieJar()
获取session
session=requests.session()
运用seleium实现模拟登陆
def getHtml(url):
browser.get(url)
browser.maximize_window()
browser.switch_to.frame(browser.find_element_by_xpath('//*[@id="app"]/div/section[1]/div/div[1]/iframe'))
browser.find_element_by_id('用户框xpath路径').send_keys('**** ')
browser.find_element_by_name('密码框xpath路径').send_keys('****')
div=browser.find_element_by_xpath('获取滑块的xpath路径')
#实现滑动效果
ActionChains(browser).click_and_hold(on_element=div).perform()
ActionChains(browser).move_to_element_with_offset(to_element=div, xoffset=30, yoffset=10).perform()
ActionChains(browser).move_to_element_with_offset(to_element=div, xoffset=100, yoffset=20).perform()
ActionChains(browser).move_to_element_with_offset(to_element=div, xoffset=200, yoffset=50).perform()
browser.find_element_by_xpath('登陆的按钮的xpath路径').click()
#获取cookie
cookies = browser.get_cookies()
return cookies
下面就可以传入一个url,测试是否登录成功,是否能拿到用户cookie
cookie值也拿到了,说明模拟登录成功,下面就是解析相应的接口数据。