使用Selenium Python在Chrome浏览器中无头浏览[重复]

问题描述 投票:-1回答:2

我正试图弄清楚如何使用Selenium Python在无头模式下操作网页,但我不断收到错误消息。当我运行下面的代码时,它运行没有问题。

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()

错误信息:

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\remote\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\remote\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\remote\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\remote\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)
python selenium
2个回答
0
投票

如果相关元素不在浏览器的视口中,则会发生这种情况。

这可以通过执行一些脚本或使用ActionChain滚动到元素来解决。

从这个SO问题:

driver.execute_script("arguments[0].scrollIntoView();", element)

0
投票

除了可以防止发生此错误之外,您可以尝试使用。

try :部分,你把你的点击命令。

except ElementNotVisibleException :中,您可以使用execute_script将可见性设置为可见,然后单击。

这应该是这样的

driver.execute_script("arguments[0].style.visibility = 'visible';",Element)
Element.click()
© www.soinside.com 2019 - 2024. All rights reserved.