【问题标题】:How to use HtmlUnitDriver using Selenium in python?如何在 python 中使用 Selenium 使用 HtmlUnitDriver?
【发布时间】:2021-12-17 10:32:12
【问题描述】:

我正在使用selenium-4.1.0,我正在寻找最轻量级的网络驱动程序(出于速度目的)。
我听说过HtmlUnitDriver,但是在使用 python 时,我需要在尝试使用驱动程序之前运行 selenium 服务器。 我小心地采用了与我的 selenium 版本相对应的版本(可用here),并且我完全按照步骤使其工作;但它没有。

运行java -jar selenium-server-4.1.0.jar standalone后(在localhost:4444上运行):

我试过了:

from selenium import webdriver

driver = webdriver.Remote(
    command_executor='http://localhost:4444/wd/hub', # I also tried with 'http://localhost:4444', and without 'command_executor' keyword
    desired_capabilities=webdriver.DesiredCapabilities.HTMLUNITWITHJS
)
driver.get('http://www.google.com')

我收到以下错误:

DeprecationWarning: desired_capabilities has been deprecated, please pass in an Options object with options kwarg
  driver = webdriver.Remote(

所以我将代码更改为:

from selenium import webdriver

options = webdriver.ChromeOptions()
options.headless = True

wd = webdriver.Remote('http://localhost:4444/wd/hub', options=options)

wd.get('http://www.google.com')

wd.save_screenshot('screenshot.png')

它确实有效(我得到了屏幕截图),但后来我不再使用 HtmlUnit
有谁知道出了什么问题和/或我可以做些什么来使它工作?

【问题讨论】:

  • 因为HtmlUnit是无头浏览器(模拟)所以不支持图片截图。

标签: python selenium selenium-webdriver htmlunit-driver


【解决方案1】:

在python库中selenium最好截图。在下面的代码中,如果你需要,我也会保持 URL 滚动,你不能离开它。

在此您要检查 chrome 版本并安装 chrome 驱动程序。我的 chrome 版本是 96.0.4664.110 下载驱动并安装

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

options = webdriver.ChromeOptions()
options.headless = True
driver = webdriver.Chrome(options=options)

URL = "D:\watermark"
driver.get(URL)

S = lambda X: driver.execute_script('return 
document.body.parentNode.scroll'+X)
driver.set_window_size(S('Width'),S('Height')) # May need manual adjustment
#time.sleep(60)                                                                                                                
driver.find_element_by_tag_name('body').screenshot('web_screenshot.png')
driver.quit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    相关资源
    最近更新 更多