【问题标题】:Grabing text using Selenium/XPath/Python使用 Selenium/XPath/Python 抓取文本
【发布时间】:2020-12-29 03:12:10
【问题描述】:

我想从Johns Hopkins Covid dashboard 中获取总死亡人数。我想使用 Selenium、Python 和 Selenium 的 chrome 驱动程序来做到这一点。死亡人数可以在路径//*[@id="ember1915"]/svg/g[2]/svg/text下找到。

这是我的脚本:

from selenium.webdriver import Chrome
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

with Chrome() as driver:
    driver.get('https://coronavirus.jhu.edu/map.html')
    driver.implicitly_wait(20) # Waits for 20 s for the entire page to loads.
    

    diplayElement = driver.find_element_by_xpath('//*[@id="ember1915"]/svg/g[2]/svg/text')

它失败并出现错误“没有这样的元素:

Unable to locate element: {"method":"xpath","selector":"//*[@id="ember1915"]/svg/g[2]/svg/text"}”.

这也发生在我试图抓取的其他网站上。

我该如何解决这个问题?这个错误的原因是什么?

【问题讨论】:

    标签: python selenium svg xpath webdriverwait


    【解决方案1】:

    Johns Hopkins Covid dashboard 中死亡总数的元素,即 905,181<iframe> 内,因此您必须:

    • 诱导WebDriverWait 使所需的帧可用并切换到它

    • WebDriverWait 诱导为visibility_of_element_located(),您可以使用以下任一Locator Strategies

      • 使用XPATHget_attribute()

        driver.get('https://coronavirus.jhu.edu/map.html')
        WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='Coronavirus COVID-19 Global Cases by Johns Hopkins CSSE']")))
        print(WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.XPATH, "//*[name()='svg']/*[name()='text' and text()='Global Deaths']//following::div[1]/*[name()='svg' and @class='responsive-text-group']//*[name()='g' and @class='responsive-text-label']/*[name()='svg']/*[name()='text']"))).get_attribute("innerHTML"))
        
      • 使用XPATHtext 属性:

        driver.get('https://coronavirus.jhu.edu/map.html')
        WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='Coronavirus COVID-19 Global Cases by Johns Hopkins CSSE']")))
        print(WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.XPATH, "//*[name()='svg']/*[name()='text' and text()='Global Deaths']//following::div[1]/*[name()='svg']//*[name()='g']/*[name()='svg']/*[name()='text']"))).text)
        
    • 控制台输出:

      905,181
      
    • 注意:您必须添加以下导入:

      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找到相关讨论


    参考

    您可以在以下位置找到一些相关讨论:

    【讨论】:

    • 你如何确定它会在不选择 iframe 的情况下返回文本或内部 html ?即使不选择阴影元素,我也想知道它是如何做到的。
    • @Dev 不错,只是在复制代码时滑出,现在更正。
    猜你喜欢
    • 2020-10-14
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2021-07-22
    • 2014-04-25
    相关资源
    最近更新 更多