Selenium 与 Chrome 一起工作,但不是无头的 Chrome

新手上路,请多包涵

我已经使用 Selenium 开发了几个 Python 脚本,首先是 PhantomJS。在转向自动下载时,我切换到(带头的)Firefox(有效),然后切换到带有无头选项的 Chrome,这样我就不会在我面前打开浏览器。

我的第一个脚本访问一个页面和几个 HTML 元素,与无头 Chrome 完美配合。

然而,第二个 仅适用于 headed Chrome 。如果我添加“无头”选项,它就不再起作用了。当我尝试以无头模式打印 HTML 以了解为什么它找不到我正在寻找的 HTML 元素时,我所拥有的只是:

 <html xmlns="http://www.w3.org/1999/xhtml"><head></head><body></body></html>

使用 headed Chrome,我打印了一个完整的 HTML。这就是我启动无头 Chrome 的方式:

 options = webdriver.ChromeOptions()
options.add_argument("--ignore-certificate-errors")
options.add_argument("headless")
driver = webdriver.Chrome(chrome_options=options)

再次注意,这适用于我的另一个脚本。这里唯一的区别是我需要登录才能访问该页面,但即便如此,它为什么会与 head 一起工作?我的脚本是通过填写表格自动登录的。

Python:3.6.1,Chrome:60.0.3112.78(64 位),Selenium:3.4.3

任何的想法?谢谢。

\*\* 编辑:这是代码的开头**

 url = 'https://10.11.227.21/tmui/'
driver.get(url + "login.jsp")

html_source = driver.page_source
print(html_source)

blocStatus = WebDriverWait(driver, TIMEOUT).until(EC.presence_of_element_located((By.ID, "username")))
inputElement = driver.find_element_by_id("username")
inputElement.send_keys('actualLogin')
inputElement = driver.find_element_by_id("passwd")
inputElement.send_keys('actualPassword')
inputElement.submit()

原文由 Gnougnou 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 375
2 个回答

我和你有同样的经历,用xvfb和pyvirtualdisplay解决了。

我使用 chromedrive=v2.3.1、chrome-browser=v60 和 Selenium=3.4.3

在 Headless chrome 中,某些脚本似乎无法按预期工作。

请参考 vpassapera 在 https://gist.github.com/addyosmani/5336747 中的评论。

像下面这样试试怎么样,

 from pyvirtualdisplay import Display

display = Display(visible=0, size=(800, 600))
display.start()

# Do Not use headless chrome option
# options.add_argument('headless')

url = 'https://10.11.227.21/tmui/'
driver.get(url + "login.jsp")

html_source = driver.page_source
print(html_source)

blocStatus = WebDriverWait(driver,    TIMEOUT).until(EC.presence_of_element_located((By.ID, "username")))
inputElement = driver.find_element_by_id("username")
inputElement.send_keys('actualLogin')
inputElement = driver.find_element_by_id("passwd")
inputElement.send_keys('actualPassword')
inputElement.submit()

display.stop()

xvfb 需要使用“pyvortualdisplay”

 $ sudo apt-get install -y xvfb

原文由 frank 发布,翻译遵循 CC BY-SA 3.0 许可协议

Headless Chrome 不支持不安全的证书,因此,带有不安全证书的网站不会打开,而是空白。您需要添加以下功能:

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

chrome_options = Options()
chrome_options.add_argument("--headless")

capabilities = DesiredCapabilities.CHROME.copy()
capabilities['acceptSslCerts'] = True
capabilities['acceptInsecureCerts'] = True

driver = webdriver.Chrome(chrome_options = chrome_options,executable_path='your path',desired_capabilities=capabilities)
driver.get("yourWebsite")

这将完成工作。

原文由 Suraj Regmi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题