【问题标题】:Find a <td> element using Selenium Python使用 Selenium Python 查找 <td> 元素
【发布时间】:2019-12-11 21:37:29
【问题描述】:

我是 python 新手,我正在尝试编写一个网络抓取脚本。我正在尝试双击此元素(它既不是按钮也不是链接 - 只是一个 td 元素),甚至一开始就找不到它。

下面是代码

<td align="left" valign="middle" class="   "
title="Business Profile (Imported)">Business Profile (Imported)</td>

当我选择它时,类会改变。我怀疑这就是问题所在

<td align="left" valign="middle" class="  cellselected "
title="Business Profile (Imported)">Business Profile (Imported)</td>

我使用了 css 选择器和 xpath。没有工作。我都试过了:

driver.find_element_by_xpath('//td[@title="Business Profile (Imported)"]').click()
driver.find_element_by_css_selector("td[title='Business Profile (Imported)']")

这是我得到的错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//td[@title="Business Profile (Imported)"]"}

任何帮助将不胜感激。谢谢!!

【问题讨论】:

  • 它在 IFRAME 内吗?您是否尝试过添加等待?

标签: python selenium selenium-webdriver xpath xpath-1.0


【解决方案1】:

要定位所需的&lt;td&gt; 元素,您必须为visibility_of_element_located() 诱导WebDriverWait,您可以使用以下Locator Strategies 之一:

  • XPATH1:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//td[contains(@title, 'Imported') and starts-with(., 'Business Profile')]")))
    
  • XPATH2:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//td[starts-with(@title, 'Business Profile') and contains(., 'Imported')]")))
    
  • 注意:您必须添加以下导入:

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

【讨论】:

  • 您的回答提供了 Kunduk 没有提供的什么?除了一个不太具体和令人困惑的定位器???为什么要检查标题是否包含“已导入”但包含的文本是否包含“业务简介”...为什么不检查标题或包含的文本?
【解决方案2】:

要处理动态元素,请引入 WebDriverWaitelement_to_be_clickable 并使用以下 xpath

WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//td[@title='Business Profile (Imported)' and text()='Business Profile (Imported)']"))).click()

WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//td[@title='Business Profile (Imported)'][contains(.,'Business Profile (Imported)')]"))).click()

您需要导入以下代码才能执行上述代码。

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

【讨论】:

  • 您的定位器可能不需要同时检查标题和包含的文本。我认为两者都足够了。
猜你喜欢
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
相关资源
最近更新 更多