【问题标题】:How to get HTML element that is before a certain class?如何获取某个类之前的 HTML 元素?
【发布时间】:2020-10-04 23:48:30
【问题描述】:

我正在抓取并且无法获取位于包含“type2”类的另一个“th”元素之前的“th”标签元素。我更喜欢通过识别它是“type2”类的“th”之前的元素“th”来接受它,因为我的 HTML 有很多“th”,这是我在表格之间发现的唯一区别。

使用 rvest 或 xml2(或其他 R 包),我可以获得这个父级吗? 我想要的内容是“text_that_I_want”。

谢谢!

<tr>
    <th class="array">text_that_I_want</th>
    <td class="array">
        <table>
            <thead>
                <tr>
                    <th class="string type2">name</th>
                    <th class="array type2">answers</th>
                </tr>
            </thead>

【问题讨论】:

  • 这是来自可公开查看的网页吗?

标签: html r web-scraping rvest xml2


【解决方案1】:

相对于给定节点导航 xpath 的正式且更通用的方法是通过ancestorpreceding-sibling

read_html(htmldoc) %>% 
html_nodes(xpath = "//th[@class = 'string type2']/ancestor::td/preceding-sibling::th") %>% 
html_text()
#> [1] "text_that_I_want"

【讨论】:

  • 不错!不知道:)
  • 有趣的解决方案,但它不能正常工作,因为它确实需要考虑 'type2' 类。如果它不考虑'type2'类,它也会得到错误的内容
【解决方案2】:

我们可以在所有&lt;th&gt;s中查找“type2”字符串,得到第一次出现的索引,减去1得到我们想要的索引:

library(dplyr)
library(rvest)

location <- test%>% 
  html_nodes('th') %>% 
  str_detect("type2")

index_want <- min(which(location == TRUE) - 1)

test%>% 
  html_nodes('th') %>%
  .[[index_want]] %>% 
  html_text()

[1] "text_that_I_want"

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 2021-07-02
    • 2011-10-11
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    相关资源
    最近更新 更多