【问题标题】:Error on Python Selenium (find_element_by_xpath)Python Selenium 上的错误(find_element_by_xpath)
【发布时间】:2021-01-26 15:15:55
【问题描述】:

我正在尝试编写代码列表来自动化我的日常文件下载过程。我为此使用 Python Selenium。但是,我无法找到其中一个点击。

HTMI 代码如下:

<div class="card dark-blue"> <h3 data-mh="title-research" style="height: 52px;">Rated Range Prices (LT)</h3> <h4 class="disp_date">26-Jan-2021 17:47:58</h4> <div class="divider"></div> <a href="javascript:seemore('F10002');" value="F10002" class="link">See More »</a> </div>

这是我的代码:

link = driver.find_element_by_xpath("//a[@href='javascript:seemore('F10002');']")

错误信息:

InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression //*[@href='javascript:seemore('F10002');'] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*[@href='javascript:seemore('F10002');']' is not a valid XPath expression.
  (Session info: chrome=88.0.4324.104)

有人可以请教我吗?非常感谢。

【问题讨论】:

    标签: python selenium xpath css-selectors webdriverwait


    【解决方案1】:

    要定位元素查看更多»,您可以使用以下任一Locator Strategies

    • 使用css_selector

      element = driver.find_element(By.CSS_SELECTOR, "div.card.dark-blue a.link[href*='seemore']")
      
    • 使用xpath

      element = driver.find_element(By.XPATH, "//div[@class='card dark-blue']//a[@class='link' and starts-with(., 'See More')]")
      

    理想情况下,要定位 clickable 元素,您需要将WebDriverWait 诱导为visibility_of_element_located(),您可以使用以下任一Locator Strategies

    • 使用CSS_SELECTOR:

      element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.card.dark-blue a.link[href*='seemore']")))
      
    • 使用XPATH:

      element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='card dark-blue']//a[@class='link' and starts-with(., 'See More')]")))
      
    • 注意:您必须添加以下导入:

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

    【讨论】:

      【解决方案2】:

      您在另一个单引号对中使用单引号对...

      试试

      link = driver.find_element_by_xpath('''//a[@href="javascript:seemore('F10002');"]''')
      

      【讨论】:

      • 谢谢。现在语法是正确的。但是,它仍然无法定位元素。 HTMI 代码如下:

        额定范围价格(LT)

        26-Jan-2021 17:47:58

        查看更多 »
      • @EdwinSoon 检查链接是否位于 iframe 内,或者您可能需要 wait for element to be clickable
      猜你喜欢
      • 1970-01-01
      • 2022-01-11
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      相关资源
      最近更新 更多