selenium
概念:基于浏览器自动化的一个模块,可以模拟浏览器行为
- 环境的安装:下载selenium模块
- selenium和爬虫之间的关联是什么?
- 便捷的获取页面中动态加载的数据
- requests模块进行数据爬取:可见非可得
- selenium:可见即可得
- 实现模拟登录
- 便捷的获取页面中动态加载的数据
- 基本操作:
- 谷歌浏览器驱动程序下载地址:http://chromedriver.storage.googleapis.com/index.html
- 驱动程序和谷歌版本的映射关系表:https://blog.csdn.net/huilan_same/article/details/51896672
- 1.实例化某一款浏览器对象(驱动程序的路径)
- 2.find系列的函数用作于标签定位
- 动作链:一系列的行为动作
- 无头浏览器:无可视化界面的浏览器.
- phantomJS
1 百度搜索"美女",代码演示
from selenium import webdriver from time import sleep # 后面是你的浏览器驱动位置,记得前面加r'','r'是防止字符转义的 driver = webdriver.Chrome(r'D:\教学视频\python 爬虫\tools\chromedriver.exe') # 浏览器驱动路径 # 用get打开百度页面 driver.get("http://www.baidu.com") # 查找页面的“设置”选项,并进行点击 sleep(1) driver.find_elements_by_link_text('设置')[0].click() sleep(2) # 打开设置后找到“搜索设置”选项,设置为每页显示50条 driver.find_elements_by_link_text('搜索设置')[0].click() sleep(2) # 选中每页显示50条 m = driver.find_element_by_id('nr') sleep(2) m.find_element_by_xpath('//*[@id="nr"]/option[3]').click() m.find_element_by_xpath('.//option[3]').click() sleep(2) # 点击保存设置 driver.find_elements_by_class_name("prefpanelgo")[0].click() sleep(2) # 处理弹出的警告页面 确定accept() 和 取消dismiss() driver.switch_to_alert().accept() sleep(2) # 找到百度的输入框,并输入 美女 driver.find_element_by_id('kw').send_keys('美女') sleep(2) # 点击搜索按钮 driver.find_element_by_id('su').click() sleep(2) # 在打开的页面中找到“Selenium - 开源中国社区”,并打开这个页面 driver.find_elements_by_link_text('美女_百度图片')[0].click() sleep(3) # 关闭浏览器 driver.quit()
2 selenium的基本操作
from selenium import webdriver from time import sleep #实例化一个浏览器对象 bro = webdriver.Chrome(executable_path=r'C:\Users\oldboy-python\Desktop\爬虫+数据\day04\chromedriver.exe') url = 'https://www.jd.com/' bro.get(url) #用户发起请求 #定位标签 search_input = bro.find_element_by_id('key') #对指定标签进行数据交互 search_input.send_keys('macPro') btn = bro.find_element_by_xpath('//*[@id="search"]/div/div[2]/button') btn.click() sleep(2) #执行js代码 jsCode = 'window.scrollTo(0,document.body.scrollHeight)' bro.execute_script(jsCode) sleep(3) bro.quit()
3 seleniu爬取药监总局数据
# 爬取前两页,爬取动态获取到额数据 from selenium import webdriver from lxml import etree from time import sleep #实例化一个浏览器对象 page_text_list = [] bro = webdriver.Chrome(executable_path=r'./chromedriver.exe') url = 'http://125.35.6.84:81/xk/' bro.get(url) sleep(2) #page_source返回的就是当前浏览器打卡页面对应的页面源码数据 page_text = bro.page_source page_text_list.append(page_text) for i in range(2): bro.find_element_by_id('pageIto_next').click() sleep(2) page_text = bro.page_source page_text_list.append(page_text) for page_text in page_text_list: tree = etree.HTML(page_text) li_list = tree.xpath('//*[@id="gzlist"]/li') for li in li_list: name = li.xpath('./dl/@title')[0] print(name) sleep(3) bro.quit()
4 selenium 动作链
from lxml import etree from time import sleep from selenium import webdriver from selenium.webdriver import ActionChains # 实例化一个浏览器对象 page_text_list = [] bro = webdriver.Chrome(executable_path=r'./chromedriver.exe') url = 'https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable' bro.get(url) # 如果定位的标签是存在于iframe对应的子页面中的话,在进行标签定位前一定要执行一个switch_to的操作 bro.switch_to.frame('iframeResult') div_tag = bro.find_element_by_id('draggable') # 1.实例化动作链对象 action = ActionChains(bro) action.click_and_hold(div_tag) for i in range(5): # .perform()方法是让动作链立即执行 action.move_by_offset(17, 0).perform() sleep(0.5) action.release() # 释放 sleep(3) bro.quit() # 关闭浏览器
5 无头浏览器headless
- 无头浏览器是为了用户使用过程中弹出浏览器自动操作:使用chorm浏览器的无头模式
from selenium.webdriver.chrome.options import Options from time import sleep from selenium import webdriver # 创建一个参数对象,用来控制chrome以无界面模式打开 chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') # 实例化一个浏览器对象 bro = webdriver.Chrome(executable_path=r'./chromedriver.exe', chrome_options=chrome_options) bro.get('https://www.baidu.com') sleep(2) bro.save_screenshot('1.png') print(bro.page_source) sleep(2) bro.quit()
6 selenium 规避风险
- 某些网站存在selenium检测
from time import sleep from selenium import webdriver from selenium.webdriver import ChromeOptions # 实例化一个对象规避检测 option = ChromeOptions() option.add_experimental_option('excludeSwitches', ['enable-automation']) #实例化一个浏览器对象 bro = webdriver.Chrome(executable_path=r'./chromedriver.exe',options=option) bro.get('https://www.taobao.com/')
3.7 12306 模拟登录
- 使用截图,坐标定位,点击动作链技术
from selenium import webdriver from selenium.webdriver import ActionChains from PIL import Image # 用作于图片的裁剪 from ChaoJiYing import Chaojiying_Client from time import sleep bro = webdriver.Chrome(executable_path=r'./chromedriver.exe') bro.get('https://kyfw.12306.cn/otn/login/init') sleep(5) # 验证码图片进行捕获(裁剪) bro.save_screenshot('main.png') # 定位到了验证码图片对应的标签 code_img_ele = bro.find_element_by_xpath('//*[@id="loginForm"]/div/ul[2]/li[4]/div/div/div[3]/img') location = code_img_ele.location # 验证码图片基于当前整张页面的左下角坐标 size = code_img_ele.size # 验证码图片的长和宽 # 裁剪的矩形区域(左下角和右上角两点的坐标) rangle = ( int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height'])) i = Image.open('main.png') frame = i.crop(rangle) frame.save('code.png') # 使用打码平台进行验证码的识别 chaojiying = Chaojiying_Client('bobo328410948', 'bobo328410948', '899370') # 用户中心>>软件ID 生成一个替换 96001 im = open('code.png', 'rb').read() # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要// result = chaojiying.PostPic(im, 9004)['pic_str'] print(result) # x1,y1|x2,y2|x3,y3 ==> [[x1,y1],[x2,y2],[x3,y3]] all_list = [] # [[x1,y1],[x2,y2],[x3,y3]] 每一个列表元素表示一个点的坐标,坐标对应值的0,0点是验证码图片左下角 if '|' in result: list_1 = result.split('|') count_1 = len(list_1) for i in range(count_1): xy_list = [] x = int(list_1[i].split(',')[0]) y = int(list_1[i].split(',')[1]) xy_list.append(x) xy_list.append(y) all_list.append(xy_list) else: x = int(result.split(',')[0]) y = int(result.split(',')[1]) xy_list = [] xy_list.append(x) xy_list.append(y) all_list.append(xy_list) # action = ActionChains(bro) for l in all_list: x = l[0] y = l[1] ActionChains(bro).move_to_element_with_offset(code_img_ele, x, y).click().perform() sleep(1) sleep(3) bro.quit()