【问题标题】:Xpath and css_selectors fail to extract dynamic content. (Using Python and Selenium)Xpath 和 css_selectors 无法提取动态内容。 (使用 Python 和 Selenium)
【发布时间】:2020-08-25 14:24:52
【问题描述】:

编辑:感谢 E Wiest 解决了我的问题。你使用了一些我不熟悉的代码,所以你给了我一些很好的学习材料。

原帖:我在 Python 中使用 Selenium 来获取教育统计数据。我整天都在尝试从以下包含美国伊利诺伊州信息的网站中提取一个数字——长期缺勤率:https://www.illinoisreportcard.com/School.aspx?schoolid=340491250130001 该数字(在本例中为“10%”)位于在具有“解释”类的 div 元素内。

<p class="image" id="thumb6" data-type="partition">
  <svg class="canvas" width="256" height="220" viewBox="0 0 256 220">...</svg>==0
  <div class="explanation" style="position: absolute; width: 110px; text-align: center; top: 82px; left: 73px;">10%</div>
</p>

我已经尝试了以下所有方法以及更多方法,包括显式等待,以选择包含此图形的 div 元素,但都失败了,通常会导致 NoSuchElementException:

driver.find_element_by_class_name('explanation')
driver.find_element_by_xpath("//div[@class='explanation']")
#Trying to reach parent element: 
driver.find_element_by_xpath("//p[@id='thumb6']")
driver.find_element_by_xpath(/html[1]/body[1]/div[1]/div[1]/a[7]/p[1]/svg[1]/g[1]/rect[1])

我相信,但不确定,这个问题可能与动态内容有关,但我不确定 HTML 代码是否实际上是动态的,因为我以前没有遇到过。谁能帮助理解为什么我不能提取这个数字?

谢谢。非常感谢任何帮助。

【问题讨论】:

    标签: python html selenium xpath css-selectors


    【解决方案1】:

    我认为您不需要 Selenium。首先,建立一个 url 列表。模式是:

    https://rcc.isbe.net/api/reportcardservice/(en)/Domain(school)/Id(340491250130001)/(Profile)/(2019)/Table/(Xml)
    

    Id(340491250130001) 是每所学校的 id。(2019) 是感兴趣的年份。您可以根据需要指定年份范围(2016-2019)

    对于列表中的每个 url,您需要获取包含数据的资源 url。 XPath:

    //resourceUrl
    

    你会得到类似的东西:

    https://sec.isbe.net/iircapi/tempData/XML/File1992993354.xml
    

    对于每个 xml 文件,您将获得长期缺勤率:

    //ChronicAbsenteeism
    

    例如:

    from lxml import html
    import requests
    
    data = requests.get('https://rcc.isbe.net/api/reportcardservice/(en)/Domain(school)/Id(340491250130001)/(Profile)/(2019)/Table/(Xml)')
    root = html.fromstring(data.content)
    xml=root.xpath('//resourceurl/text()')[0]
    
    source = requests.get(xml)
    tree = html.fromstring(source.content)
    print(tree.xpath('//chronicabsenteeism/text()')[0])
    

    输出:10

    【讨论】:

    • 嗨,E.Wiest,这真​​的很有帮助,谢谢。您能告诉我下面的代码到底是什么,以及您是如何知道找到它的吗? rcc.isbe.net/api/reportcardservice/(en)/Domain(school)/…
    • 您可以在页面顶部下载.xlsx格式的数据。这是下载地址的一部分。
    【解决方案2】:

    下面是快速解决方法:

    driver.find_element_by_xpath("//div[@class='explanation']").text() # This will fetch the innerHTML i.e. value of the div
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      相关资源
      最近更新 更多