1

所以我一直试图让无头铬工作好几天。我不知道怎么了!我已经尝试了所有可以在与该问题相关的论坛中找到的方法。

现在这是我正在运行的代码(它是其他人教程的直接片段,对他们来说很好):

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options


browser_name = "chrome"
if browser_name == 'chrome':
    options = webdriver.ChromeOptions()
    options.headless = True
    driver = webdriver.Chrome(executable_path=r"./chromedriver", options=options)
    start_url = "https://google.com"
    driver.get(start_url)
    print(driver.page_source.encode("utf-8"))
    driver.quit()

当我运行该代码时,我收到以下错误

driver = webdriver.Chrome(executable_path=r"./chromedriver", options=options)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py", line 64, in __init__
    desired_capabilities = options.self.to_capabilities()
AttributeError: 'Options' object has no attribute 'self'

可能值得知道 chromedriver 在正确的路径中,我知道这一点,因为当我运行时:

 browser_name = "chrome"

 if browser_name == 'chrome':
    
    driver = webdriver.Chrome(r"./chromedriver")
    start_url = "https://google.com"
    driver.get(start_url)
    print(driver.page_source.encode("utf-8"))
    driver.quit()

这工作正常

4

1 回答 1

0

有两种不同的方法。如果您正在使用:

options = webdriver.ChromeOptions()

仅使用:

from selenium import webdriver

足够了。


但是,如果您使用以下导入:

from selenium.webdriver.chrome.options import Options

您必须使用 的实例Options()来设置headless属性,True如下所示:

options = Options()
options.headless = True
driver = webdriver.Chrome(executable_path=r"./chromedriver", options=options)
于 2020-11-18T14:54:15.653 回答