【问题标题】:Selenium NoSuchElementException with Valid XPath (Python)Selenium NoSuchElementException 与有效 XPath (Python)
【发布时间】:2023-03-27 21:30:02
【问题描述】:

当我运行下面的代码时,我得到selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="i0"]/input"} (Session info: chrome=83.0.4103.97)

但是,在我的终端中,我可以访问所需的元素:

>>> steam_pressure_field = browser.find_element_by_xpath('//*[@id="i0"]/input')
>>> steam_pressure_field.get_attribute('value')
'0'

正如您在代码的注释部分看到的那样,我尝试等待 3 秒的延迟,看看是否有什么不同。然而,在这样做了几次之后,当我使用延迟时页面停止加载(可能是一些反机器人功能?)

所以我试图了解这里发生了什么,以及如何成功访问我需要的字段。请问有什么遗漏的吗?

顺便说一句,div ID 似乎不是动态的。

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


user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'
options = webdriver.ChromeOptions()
options.add_argument(f'user-agent={user_agent}')
browser = webdriver.Chrome(options=options)

url = 'https://www.tlv.com/global/US/calculator/superheated-steam-table.html?advanced=off'

# delay = 3
# try:
    # wait = WebDriverWait(browser, delay)
    # wait.until(EC.presence_of_element_located((By.ID, "body")))
    # browser.get(url)
    # print("Page is ready")
# except TimeoutException:
    # print("Loading took too much time")

browser.get(url)
steam_pressure_field = browser.find_element_by_xpath('//*[@id="i0"]/input')
print(steam_pressure_field.get_attribute('value'))

【问题讨论】:

  • 当我打开该页面并“查看源代码”时,我在 HTML 中看不到该项目。

标签: python selenium-webdriver xpath css-selectors webdriverwait


【解决方案1】:

要打印值0,您必须为visibility_of_element_located() 诱导WebDriverWait,您可以使用以下任一Locator Strategies

  • 使用CSS_SELECTOR

    driver.get('https://www.tlv.com/global/US/calculator/superheated-steam-table.html?advanced=off')
    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.inputPanel>div.Controlpanel input.inputText"))).get_attribute("value"))
    
  • 使用XPATH

    driver.get('https://www.tlv.com/global/US/calculator/superheated-steam-table.html?advanced=off')
    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='InputControlLabel' and text()='Steam Pressure']//following-sibling::input[1]"))).get_attribute("value"))
    
  • 控制台输出:

    0
    
  • 注意:您必须添加以下导入:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 2013-11-24
    • 2016-04-29
    相关资源
    最近更新 更多