Navigating a website headless in Chrome using Selenium Python
本问题已经有最佳答案,请猛点这里访问。
我正试图找出如何使用SeleniumPython以无头模式操作网页,但我一直收到一条错误消息。当我运行下面可见的代码时,它运行时没有问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from selenium import webdriver from selenium.webdriver.chrome.options import Options import time options = Options() options.set_headless(headless=True) options.add_argument('window-size=1200x600') driver = webdriver.Chrome(options=options, executable_path=r'F:\\Python\\chromedriver.exe') driver.get("https://www.google.com/") element = driver.find_element_by_name('q') element.send_keys('test') test1 = driver.find_element_by_name('btnK') test1.click() print ("Test Completed") driver.quit() |
错误信息:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | Traceback (most recent call last): File"F:\Python\URLtest.py", line 154, in <module> test1.click() File"C:\Users\User1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium-3.14.0-py3.6.egg\selenium\webdriver emote\webelement.py", line 80, in click self._execute(Command.CLICK_ELEMENT) File"C:\Users\User1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium-3.14.0-py3.6.egg\selenium\webdriver emote\webelement.py", line 628, in _execute return self._parent.execute(command, params) File"C:\Users\User1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium-3.14.0-py3.6.egg\selenium\webdriver emote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File"C:\Users\User1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium-3.14.0-py3.6.egg\selenium\webdriver emote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotVisibleException: Message: element not visible (Session info: headless chrome=68.0.3440.106) (Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e),platform=Windows NT 6.1.7601 SP1 x86_64) |
如果相关元素不在浏览器的视图端口中,则可能发生这种情况。
这可以通过执行一些脚本或使用
从这个问题:
1 | driver.execute_script("arguments[0].scrollIntoView();", element) |
您可以使用"尝试",但可以防止发生此错误。
在
在
这个应该看起来像
1 2 | driver.execute_script("arguments[0].style.visibility = 'visible';",Element) Element.click() |