【问题标题】:Copied xpath directly from chrome, and not working直接从chrome复制xpath,不工作
【发布时间】:2022-01-22 10:34:17
【问题描述】:

试图从 fanduel 中获取赔率,目标是获得玩家的名字。在这种情况下,杰森·塔图姆。

https://sportsbook.fanduel.com/basketball/nba/philadelphia-76ers-@-boston-celtics-31137202?tab=player-points

即使我直接从 chrome 复制 xpath,它似​​乎也不起作用。虽然它在我硬编码并通过包含文本 Jayson Tatum 的 xpath 查找元素时有效。 这是我的代码

name = WebDriverWait(driver, 20).until(
                    EC.presence_of_element_located((By.XPATH,'//*[@id="root"]/div/div[2]/div[1]/div/div[2]/div[3]/div/div[2]/div/div[3]/div[1]/div/div/div[1]/span')))

也试过了

name = driver.find_element(By.XPATH, '//*[@id="root"]/div/div[2]/div[1]/div/div[2]/div[3]/div/div[2]/div/div[3]/div[1]/div/div/div[1]/span')

尝试两种方式仍然得到 NoSuchElement。

【问题讨论】:

    标签: python selenium selenium-webdriver xpath webdriverwait


    【解决方案1】:

    要打印文本Jayson Tatum,您可以使用以下Locator Strategy

    • 使用xpathtext属性:

      print(driver.find_element(By.XPATH, "//span[text()='UNDER']//following::div[1]//span").text)
      

    理想情况下,您需要为visibility_of_element_located() 诱导WebDriverWait,您可以使用以下任一Locator Strategy

    • 使用 XPATHget_attribute("innerHTML"):

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[text()='UNDER']//following::div[1]//span"))).get_attribute("innerHTML"))
      
    • 注意:您必须添加以下导入:

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

    您可以在How to retrieve the text of a WebElement using Selenium - Python找到相关讨论


    参考文献

    链接到有用的文档:

    【讨论】:

    • 非常感谢您的帮助!对我的旅程非常彻底和有帮助!
    猜你喜欢
    • 2019-12-04
    • 2023-03-06
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 2014-01-09
    • 1970-01-01
    相关资源
    最近更新 更多