欢迎来到赛兔子家园

selenium基础操作

selenium

概览:基于浏览器自动化的模块

自动化:可以通过代码指定一些列的行为动作,然后将其作用到浏览器。

安装:pip install selenium

selenium和爬虫之间的关联

  1. 便捷的捕获到任意形式动态加载的数据(可见即可得)
  2. 实现模拟登录

实例:

需求:打开京东后搜索文本框在输入iphoneX后点击搜索,进入到搜索页面后将滚轮滑动到浏览器最底部

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: 青城子
# datetime: 2021/7/18 16:15 
# ide: PyCharm
from selenium import webdriver
from time import sleep

# 基于浏览器的驱动程序实例化一个浏览器对象
bro = webdriver.Chrome()
# 对目的网站发起请求
bro.get("https://www.jd.com/")
# 标签定位
# send_keys()向定位标签中录入数据
bro.find_element_by_xpath('//*[@id="key"]').send_keys("iphoneX")
bro.find_element_by_xpath('//*[@id="search"]/div/div[2]/button').click()
sleep(2)
# 在搜索结果页面进行滚动操作,(执行js操作,即js注入)
bro.execute_script('window.scrollTo(0,document.body.scrollHeight)')
sleep(2)
bro.quit()

 百度例子:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: 青城子
# datetime: 2021/7/18 16:15 
# ide: PyCharm
from selenium import webdriver
from time import sleep

# 基于浏览器的驱动程序实例化一个浏览器对象
driver = webdriver.Chrome()
driver.maximize_window()
# 用get打开百度页面
driver.get("https://www.baidu.com/")
# 查找页面的【设置】选项,并进行点击
driver.find_element_by_xpath('//*[@id="s-usersetting-top"]').click()
sleep(2)
# 打开设置后找到【搜索设置】选项,设置每页显示50条
driver.find_element_by_xpath('//*[@id="s-user-setting-menu"]/div/a[1]').click()
sleep(2)
# 设置50条
driver.find_element_by_xpath('//*[@id="nr_3"]').click()
# 点击保存设置
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)
# 打开的页面中找到美女,点击第一张美女图片进入详情页面
driver.find_element_by_xpath('//*[@id="1"]/div/div[1]/div/div[1]/a[1]/img').click()
sleep(3)
# 关闭浏览器
driver.quit()
如何捕获动态加载的数据

药监总局为例:http://scxk.nmpa.gov.cn:81/xk/

获取前三页所有企业名称

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: 青城子
# datetime: 2021/7/18 17:11
# ide: PyCharm

from selenium import webdriver
from time import sleep
from lxml import etree

url = "http://scxk.nmpa.gov.cn:81/xk/"

driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)
page_text_list = []  # 每一页的页面源码数据
sleep(1)
# 捕获到当前(第一页)页面对应的页面源码数据
page_text = driver.page_source  # 当前页面全部加载完毕后对应的页面源码数据
page_text_list.append(page_text)

# 点击下一页(即第2页和第3页)
for i in range(2):
    next_page = driver.find_element_by_xpath('//*[@id="pageIto_next"]').click()
    sleep(1)
    page_text_list.append(driver.page_source)

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(2)
driver.quit()

 selenium的缺点

  • 效率低
动作链ActionChains

动作链:一系列连续的动作(滑动动作)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: 青城子
# datetime: 2021/7/18 17:34 
# ide: PyCharm

from time import sleep
from selenium import webdriver
from selenium.webdriver import ActionChains  # 动作链
from lxml import etree

url = "https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable"

driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)
sleep(1)
# 如果通过find系列的函数进行标签定位,如果标签是存在于iframe下面,则会定位失败
# 解决方案:使用switch_to即可
driver.switch_to.frame("iframeResult")
div_tag = driver.find_element_by_xpath('//*[@id="draggable"]')
# print(div_tag)
# 对div_tag进行滑动操作
action = ActionChains(driver)  # 实例化动作链,传入浏览器对象,让动作链和当前浏览器产生关联
action.click_and_hold(div_tag)  # 点击且长按,传入需要长按的参数对象

for i in range(6):
    # perform()让动作链立即执行
    action.move_by_offset(10, 15).perform()  # 偏移右下角 ,向右偏移10个像素,向下偏移15个像素
    sleep(0.5)

action.release() # 释放
driver.close()
无头浏览器

无可视化界面的浏览器 : 谷歌无头浏览器(推荐)、phantomJS

需求:使用谷歌无头浏览器访问百度页面,且将百度页面截图保存到本地

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: 青城子
# datetime: 2021/7/18 18:10 
# ide: PyCharm

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from time import sleep

# 创建一个参数对象,用例控制chrom以无界面模式打开
# 固定写法
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options=chrome_options)

driver.maximize_window()
driver.get("https://www.baidu.com/")
sleep(3)
# 截图
driver.save_screenshot("baidu.png")
print(driver.page_source)
print(driver.current_url)
 如何让selenium规避检测

有的网站会检测请求是否为selenium发起,如果是则让该次请求失败;

规避检测的方法:

selenium接管chrome浏览器

实现步骤:

1、必须将电脑中安装谷歌浏览器的启动程序所在的目录找到,且将目录添加到环境变量中。

2、打开cmd,在命令行输入命令:- chrome.exe --remote-debugging-port=9222 --user-data-dir="空文件夹目录" 

      指定执行结束后,会打开本机安装好的谷歌浏览器。

3、执行如下代码:使用下面代码接管步骤2打开的真实的浏览器。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: 青城子
# datetime: 2022/2/7 13:27 
# ide: PyCharm

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
# 本机安装谷歌浏览器驱动程序路径
chrome_driver = "C:\Python\Python37\chromedriver"

driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)
print(driver.title)

posted on 2021-07-18 16:41  赛兔子  阅读(129)  评论(0编辑  收藏  举报

导航