所以我几天来一直在努力让无头铬工作。我不知道出了什么问题!我已经尝试了在论坛中可以找到的与该问题相关的所有内容。
现在这是我正在运行的代码(这是其他人教程中的直接片段,对他们来说效果很好):
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()
这个效果很好
有两种不同的方法。如果您正在使用:
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)
使用Robot-Framework SeleniumLibrary打开浏览器时遇到类似的错误:
robot.errors.HandlerExecutionFailed: AttributeError: 'Options' object has no attribute ''
显然,
options
参数是一个用;
分隔的字符串,不应该以;
结尾,例如:
add_argument("--忽略证书错误");add_argument("window-size=1920,1024");add_argument('--no-sandbox');add_argument('--disable-gpu');add_argument ('--disable-dev-shm-usage');
一旦我删除了最后一个
;
,浏览器就会启动并带有所需的选项。