【问题标题】:Error When Trying to Click on an `a` Tag - Selenium Python尝试单击“a”标记时出错 - Selenium Python
【发布时间】:2021-08-30 15:32:05
【问题描述】:

我有一个非常简单的程序,可以打开https://google.com 并点击第一个链接。我已经使用WebDriverWait 来确保该元素已准备好被点击,尽管它仍然不起作用,并且输出和错误。

代码:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
import time

wd = webdriver.Firefox()

wd.get("https://www.google.com/search?q=python")

# wd.find_element_by_css_selector("a").click()  # This doesn't work, same error
WebDriverWait(wd, 1000000).until(
    expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, "a"))
).click()

time.sleep(5)

wd.close()

错误:

Traceback (most recent call last):
  File "c:\Users\ketha\OneDrive\Documents\Coding\Youngwonks\InteractingWithWebsites\selenium_basics.py", line 17, in <module>
    WebDriverWait(wd, 1000000).until(
  File "C:\Users\ketha\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Users\ketha\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\ketha\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\ketha\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: Element <a class="gyPpGe"> could not be scrolled into view

我正在使用 Firefox。
Firefox 版本:89.0(64 位)
硒版本:3.141.0
壁虎驱动版本:0.29.1

【问题讨论】:

    标签: python selenium selenium-webdriver firefox geckodriver


    【解决方案1】:

    您使用了错误的定位器。
    绝对不是所有的 a 元素都是链接,尤其是该页面上的第一个 a
    尝试改用这个:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions
    import time
    
    wd = webdriver.Firefox()
    
    wd.get("https://www.google.com/search?q=python")
    
    # wd.find_element_by_css_selector("a").click()  # This doesn't work, same error
    WebDriverWait(wd, 20).until(
        expected_conditions.element_to_be_clickable((By.XPATH, "//div[@id='search']//a[contains(@href,'http')]"))
    ).click()
    
    time.sleep(5)
    
    wd.close()
    

    此外,无需为显式等待定义如此长的超时。大多数情况下 20-30 秒就足够了。

    【讨论】:

      猜你喜欢
      • 2021-10-09
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 2016-01-19
      • 2019-10-02
      • 2021-06-29
      相关资源
      最近更新 更多