【问题标题】:AttributeError: 'Options' object has no attribute 'set_headless'AttributeError:“选项”对象没有属性“set_headless”
【发布时间】:2021-11-26 14:12:39
【问题描述】:

我尝试使用无头谷歌浏览器在 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)

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

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

我应该怎么做才能让它工作?

【问题讨论】:

    标签: python-3.x selenium


    【解决方案1】:

    代替

    opts = Options()
    opts.set_headless()
    

    请使用

    options = ChromeOptions()
    options.add_argument("--headless")
    

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

    进口:

    from selenium.webdriver.chrome.options import Options as ChromeOptions
    

    【讨论】:

      猜你喜欢
      • 2022-06-23
      • 2015-09-16
      • 1970-01-01
      • 2012-12-01
      • 2021-04-19
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      相关资源
      最近更新 更多