Python 中 selenium 设置参数,不打开可视化页面,后台执行爬虫程序

发布于:2022-11-29 ⋅ 阅读:(479) ⋅ 点赞:(0)

前言

        在使用 selenium 浏览器渲染技术,爬取网站信息时,默认情况下就是一个普通的纯净的 chrome 浏览器,而我们平时在使用浏览器时,经常就添加一些插件,扩展,代理之类的应用。相对应的,当我们用chrome浏览器爬取网站时,可能需要对这个chrome做一些特殊的配置,以满足爬虫的行为。

        常用的控制行为有:

  1. 禁止图片和视频的加载:提升网页加载速度。
  2. 添加代理:用于翻墙访问某些页面,或者应对IP访问频率限制的反爬技术。
  3. 使用移动头:访问移动端的站点,一般这种站点的反爬技术比较薄弱。
  4. 添加扩展:像正常使用浏览器一样的功能。
  5. 设置编码:应对中文站,防止乱码。
  6. 阻止JavaScript执行。

正文

        小编常用的功能就是:禁用浏览器启动,让 selenium 操作的就像 BeautifulSoup 那样后台执行。

1. 禁用前

        随便展示一段 selenium 操作的代码,流程如下:打开网页 → 输入搜索内容 → 触发搜索→ 滑动页面→ 关闭网页。

  • 代码展示
#_*_coding:utf-8_*_
import time
from selenium.webdriver.common.keys import Keys                     # 模仿键盘,操作下拉框的
from selenium import webdriver                                      # selenium驱动
from selenium.webdriver.support.wait import WebDriverWait           # 导入等待类
from selenium.webdriver.support import expected_conditions as EC    # 等待条件
from selenium.webdriver.common.by import By                         # 节点定位

def test_open():
    print("—————————— open ——————————")
    # 方式一:默认打开浏览器驱动
    driver = webdriver.Chrome()
    # 方式二:通过设置参数,不打开浏览器
    # driver = webdriver.Chrome(options=add_options())
    driver.get('https://www.jd.com/')
    driver.implicitly_wait(5)
    # 找到id=key的标签
    _input = driver.find_element(By.ID,'key')
    # 输入内容,查询商品信息
    _input.send_keys('iphone14')
    time.sleep(1)
    _input.clear()
    time.sleep(1)
    _input.send_keys('华为mate50pro')
    time.sleep(1)
    _input.send_keys(Keys.ENTER)
    # 触发点击事件的两种方式:1.调用键盘回车键;2.触发按钮的click事件
    # driver.find_element(By.CLASS_NAME, 'button.cw-icon').click()
    # 等待商品列表加载
    wait = WebDriverWait(driver, 5)
    wait.until(EC.presence_of_element_located((By.ID, "J_goodsList")))
    # 滚动到页面底部
    driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
    time.sleep(1)
    # 滚动到页面顶部
    driver.execute_script('window.scrollTo(0,0)')
    time.sleep(1)
    # 打印看看商品信息
    list = driver.find_elements(By.CLASS_NAME, "gl-item")
    for item in list:
        print(item.text)
    driver.close()
    pass

if __name__ == "__main__":
    test_open()
    print("—————————— end ——————————")
  • 效果展示:不仅有程序执行,还会打开浏览器且有操作效果


2. 禁用后

        除非是在测试阶段,否则每次执行程序都要弹出一个网页确实非常不友好,我们可以通过设置 chrome 浏览器的 options 参数禁用浏览器功能。

options.add_argument('--headless'):无浏览器模式

  • 代码展示:将【禁用前】的代码中,注册selenium驱动的方式切换到【方式二】,然后加入下面的代码。
def add_options():
    print("—————————— options ——————————")
    # 创建谷歌浏览器驱动参数对象
    chrome_options = webdriver.ChromeOptions()
    # 不加载图片
    prefs = {"profile.managed_default_content_settings.images": 2}
    chrome_options.add_experimental_option("prefs", prefs)
    # 使用无界面浏览器模式!!
    chrome_options.add_argument('--headless')
    # 使用隐身模式(无痕模式)
    chrome_options.add_argument('--incognito')
    # 禁用GPU加速
    chrome_options.add_argument('--disable-gpu')
    return chrome_options
  • 效果展示:没有浏览器,只有后台执行效果


3. 其他参数

        因为 ChromeOptions 的参数比较多,少部分未经验证,请见谅...

参数 说明
options.add_argument('--disable-infobars')  禁止策略化
options.add_argument('--no-sandbox') 解决DevToolsActivePort文件不存在的报错
options.add_argument('window-size=1920x3000') 指定浏览器分辨率
options.add_argument('--disable-gpu') 谷歌禁用GPU加速
options.add_argument('--disable-javascript') 禁用javascript
options.add_argument('--incognito') 隐身模式(无痕模式)
options.add_argument('--start-maximized') 最大化运行(全屏窗口),不设置,取元素会报错
options.add_argument('--hide-scrollbars') 隐藏滚动条, 应对一些特殊页面
options.add_argument('blink-settings=imagesEnabled=false') 不加载图片, 提升速度
options.add_argument('--headless') 浏览器不提供可视化页面(无头模式). linux下如果系统不支持可视化不加这条会启动失败
options.add_argument('disable-infobars') 去掉Chrome提示受到自动软件控制
options.add_argument('lang=en_US') 设置语言
options.add_argument('User-Agent=xxxxxx') 设置User-Agent属性
options.add_argument('--kiosk-printing')  默认打印机进行打印
options.binary_location = r"...\chrome.exe" 手动指定使用的浏览器位置
options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")  调用原来的浏览器,不用再次登录即可重启

prefs = {"":""}

prefs["credentials_enable_service"] = False

prefs["profile.password_manager_enabled"] = False

options.add_experimental_option("prefs", prefs) 

设置prefs属性,屏蔽'保存密码'提示框
options.add_experimental_option('excludeSwitches', ['enable-automation']) 以开发者模式启动调试chrome,可以去掉提示受到自动软件控制
options.add_experimental_option('useAutomationExtension', False)  去掉提示以开发者模式调用
options.add_argument(’–disable-setuid-sandbox’) 禁用沙盒
options.add_argument(“–disable-popup-blocking”) 允许弹窗
options.add_argument(’–disable-notifications’) 禁用通知警告
options.add_argument(’–allow-running-insecure-content’) 允许运行不安全的内容

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到