一、selenium在爬虫中的应用:
- 获取动态网页中的数据,一些动态的数据我们在获取的源码中并没有显示这一类动态加载数据
- 用户模拟登录
# 能不能让我的程序连接到浏览器·让浏览器来完成各种复杂的操作,我们只接受最终的结果
#selenium:自动化测试工具
# 可以:打开浏览器。然后像人一样去操作浏览器
# 程序员可以从selenium中直接提取网页上的各种信息
#环境搭建:
# pip install selenium-i清华源
# 下载浏览器驱动:https:/npm.taobao.org/mirrors/chromedriver
# 把解压缩的浏览器驱动 chromedriver 放在python解释器所在的文件夹
# 让selenium启动谷歌浏览器
from selenium.webdriver import Chrome
#1,创建浏览器对象
web = Chrome()
#2.打开一个网址
web.get("http://www.baidu.com")
print(web.title)
二、selenium元素定位技巧
Selenium提供了8种定位方式
id,name,class name, tag name, link text , partial link text, xpath , css selector
selenium 控制浏览器
- 设置浏览器宽480、高800显示
web.set_window_size(480,800)
- 控制浏览器前进、后退、刷新
web.back()、web.forward()、web.refresh()
selenium控制鼠标
- perform():执行所有ActionChains中存储的行为;
- context_click() :右击;
- double_click():双击
- drag_and_drop():拖动
- move_to_element():鼠标悬停
import time from selenium.webdriver import Chrome from selenium.webdriver.common.action_chains import ActionChains web.get('https://www.baidu.com') web.maximize_window() above = web.find_element_by_xpath('//*[@id="s-usersetting-top"]') # 鼠标点击 move_to_element移动到相关元素, perform执行所有的操作 ActionChains(web).move_to_element(above).perform() time.sleep(5) web.quit()
selenium设置元素等待
WebDriver提供两种类型的等待:显示等待和隐式等待
显示等待:
明确要等到某个元素的出现或者是某个元素的可点击等条件,等不到,就一直等,除非在规定的时间之内都没找到,那么就跳除Exception
import time from selenium.webdriver import Chrome # 简写用包 from selenium.webdriver.common.by import By # 等待用包 from selenium.webdriver.support.ui import WebDriverWait # 场景判断,用来判断某个元素是否出现 from selenium.webdriver.support import expected_conditions as EC web = Chrome() web.get('https://www.baidu.com') # 浏览器最大化 web.maximize_window() # WebDriverWait 设置显示等待 # 参数 web , 2. timeout 3.轮询参数,隔多久查看一次 # until ,EC场景判断,通过id来找相关元素kw element = WebDriverWait(web,5,0.5).until(EC.presence_of_element_located((By.ID,'kw'))) element.send_keys('python') time.sleep(2) web.quit()
隐式等待:
当脚本执行到某个元素定位时,如果元素可以定位,则继续执行,如果元素定位不到,则它将以轮询的方式不断地判断元素是否被定位到
import time from selenium.webdriver import Chrome # 隐式等待 from selenium.common.exceptions import NoSuchElementException web = Chrome() # 隐式等待 # 5秒找不到目标元素会报错 web.implicitly_wait(5) try: web.get('https://www.baidu.com') web.find_element_by_id('kw').send_keys('python') time.sleep(2) except NoSuchElementException as e: print(e) finally: web.quit()
爬取
import time
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
web = Chrome()
web.get('http://lagou.com')
# 找到元素点击它
el = web.find_element_by_xpath('//*[@id="changeCityBox"]/p[1]/a')
el.click() # 点击事件
time.sleep(1) # 让浏览器缓一下
# 找到输入框,输入python 按下回车搜索
web.find_element_by_xpath('//*[@id="search_input"]').send_keys('python',Keys.ENTER)
# 查找数据位置,进行数据提取
# lis = web.find_elements_by_xpath('//*[@id="jobList"]/div[1]/div')
# time.sleep(3)
# for item in lis:
# job_name = item.find_element_by_xpath('./div/div/div/a').text
# job_price = item.find_element_by_xpath('./div/div/div[2]/span[1]').text
#
# print(job_name,job_price)
web.find_element_by_xpath('//*[@id="jobList"]/div[1]/div[1]/div[1]/div[1]/div[1]/a').click()
# 切换到浏览器打开的最后一个窗口
web.switch_to.window(web.window_handles[-1])
# 提取新窗口中内容
job_desc = web.find_element_by_xpath('//*[@id="job_detail"]/dd[2]/div').text
print(job_desc)
# 关闭子窗口
web.close()
# 变更selenium窗口视角,回到原来的窗口中
web.switch_to.window(web.window_handles[0])
select下拉列表处理
from selenium.webdriver import Chrome
from selenium.webdriver.support.select import Select
web Chrome()
web.get("https://www.endata.com.cn/Boxoffice/BO/Year/index.html")
#定位到下拉列表
sel_el web.find_element_by_xpath('//*[@id="OptionDate"]')
#对元素进行包装,包装成下拉菜单
sel = Select(sel_el)
#让浏览器进行调整选项
for i in range(len(sel.options)):#i就是每一个下拉框选项的索引位置
sel.select_.by_index(i)#按照索引进行切换
无头浏览器,不打开浏览器爬取
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.select import Select
import time
#准备好参数配置
opt = Options()
apt.add_argument("--headless")
opt.add_argument("--disbale-gpu")
web = Chrome(options=opt)
#把参数配置设置到浏览器中
登录12306
import time
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options # 关闭浏览器验证
from selenium.webdriver.common.action_chains import ActionChains # 拖动滑块包
option = Options()
option.add_argument('--disable-blink-features=AutomationControlled') # 无头模式,防检测
web = Chrome(options=option)
web.get('https://kyfw.12306.cn/otn/resources/login.html')
web.find_element_by_xpath('//*[@id="J-userName"]').send_keys('111111.com') # 账号
web.find_element_by_xpath('//*[@id="J-password"]').send_keys('11111') # 密码
web.find_element_by_xpath('//*[@id="J-login"]').click()
time.sleep(5)
btn = web.find_element_by_xpath('//*[@id="nc_1__scale_text"]/span')
ActionChains(web).drag_and_drop_by_offset(btn,305,0).perform() # 拖动滑块