AttributeError:“选项”对象没有属性“set_headless”

Dol*_*hin 5 selenium python-3.x

我尝试使用无头谷歌浏览器在 macOS Big Sur 中抓取一些网站内容,这是我的 python 3 代码:

from webbrowser import Chrome
from dolphin.common.commonlogger import CommonLogger
from selenium.webdriver import chrome
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys


class FetchMusic:

    def __init__(self):
        print("fetch...")


if __name__ == '__main__':
    opts = Options()
    opts.set_headless()
    assert opts.headless  # Operating in headless mode
    browser = Chrome(executable_path=r"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
                     options=opts)
    browser.implicitly_wait(3)
    browser.get('https://ca.finance.yahoo.com/quote/AMZN/profile?p=AMZN')
    results = browser.find_elements_by_xpath('//*[@id="quote-header-info"]/div[3]/div/div/span[1]')
    for result in results:
        print(result.text)
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,显示错误:

Traceback (most recent call last):
  File "/Users/dolphin/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/212.5457.59/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py", line 1483, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Users/dolphin/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/212.5457.59/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/dolphin/source/reddwarf/backend/pydolphin/dolphin/biz/music/fetch.py", line 18, in <module>
    opts.set_headless()
AttributeError: 'Options' object has no attribute 'set_headless'
python-BaseException

Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)

我应该怎么做才能让它发挥作用?

cru*_*dey 8

代替

opts = Options()
opts.set_headless()
Run Code Online (Sandbox Code Playgroud)

请用

options = ChromeOptions()
options.add_argument("--headless")
Run Code Online (Sandbox Code Playgroud)

或者

options = Options()
options.add_argument("--headless")
Run Code Online (Sandbox Code Playgroud)

进口:

from selenium.webdriver.chrome.options import Options as ChromeOptions
Run Code Online (Sandbox Code Playgroud)