我的硒程序找不到元素

问题描述 投票:0回答:3

我正在尝试在 Chrome 中使用 python 和 selenium 执行网络自动化。 问题是我试图找到一个没有 id 或类名的按钮。

xpath 是:

 //*[@id="Form1"]/table[1]/tbody/tr/td/div/div[2]/table/tbody/tr[3]/td/span[1]

html代码是

<span class="SectionMethod" onclick="window.location.href=&quot;explorer/explorer.aspx?root=user&quot;;" style="cursor:pointer;text-decoration:underline;color:CadetBlue;">Open</span>

这是一个名为“打开”的按钮,但还有其他类似的按钮具有相同的文本和类别,因此我无法通过文本找到。

这是我的代码:

from selenium import webdriver


driver = webdriver.Chrome(chrome_options=chromeOptions, desired_capabilities=chromeOptions.to_capabilities())

driver.get("..............") 


driver.find_element_by_xpath('//*[@id="Form1"]/table[1]/tbody/tr/td/div/div[2]/table/tbody/tr[3]/td/span[1]')

这是我收到的错误:

NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"Form1"}
  (Session info: chrome=75.0.3770.100)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.16299 x86_64).
python selenium xpath css-selectors webdriverwait
3个回答
3
投票

您可能正在寻找一个元素加载之前。根据文档中的示例

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

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()

您的情况:

EC.presence_of_element_located((By.ID, "myDynamicElement"))

将会

EC.presence_of_element_located((By.XPATH, '//*[@id="Form1"]/table[1]/tbody/tr/td/div/div[2]/table/tbody/tr[3]/td/span[1]'))

1
投票

您正确的 xpath 是:

//span[@class='SectionMethod' and text() = 'Open']


1
投票

大概您正在尝试在

click()
元素上使用
<span>
并将文本设置为 Open,并且要实现这一点,您必须为 element_to_be_clickable() 引入
WebDriverWait
,并且您可以使用以下解决方案之一:

  • 使用

    CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.SectionMethod[onclick*='explorer/explorer']"))).click()
    
  • 使用

    XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='SectionMethod' and contains(@onclick,'explorer/explorer')][text()='Open']"))).click()
    
  • 注意:您必须添加以下导入:

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

此外,当您使用

chrome=75.0.3770.100
时,您需要将 ChromeDriver 更新为 ChromeDriver 75.0.3770.90 (2019-06-13)

© www.soinside.com 2019 - 2024. All rights reserved.