【问题标题】:How to get HTML element considering later content of another tag and not the class?考虑到另一个标签的后续内容而不是类,如何获取 HTML 元素?
【发布时间】:2020-06-16 14:35:45
【问题描述】:

我正在将 HTML 转换为漂亮整洁的 CSV。我有一个充满表格和类的文件。我有三种类型的表,它们的结构是相同的。唯一的区别是我感兴趣的元素之后的“th”元素中的内容。如何仅获取在“th”(“text_that_I_want_to_get”)中具有特定文本的表的内容?有没有办法在每种类型的表中插入一个带有 R 的类?

表格类型 1

 <tr>
    <th class="array">text_that_I_want_to_get</th>
    <td class="array">
        <table>
            <thead>
                <tr>
                    <th class="string">name</th>
                    <th class="string">mean</th>
                    <th class="string">stdev</th>
                </tr>
            </thead>
            <tbody>

表格类型 2

<tr>
    <th class="array">text_that_I_want_to_get</th>
    <td class="array">
        <table>
            <thead>
                <tr>
                    <th class="string">name</th>
                    <th class="array">answers</th>
                </tr>
            </thead>
            <tbody>

表格类型 3

<tr>
    <th class="array">text_that_I_want_to_get</th>
    <td class="array">
        <table>
            <thead>
                <tr>
                    <th class="string">Reference</th>
                </tr>
            </thead>
            <tbody>

【问题讨论】:

  • html 代码是否会在 R 中夹住字符对象?如果是这样你可以试试sub(".*&lt;th class="array"&gt;(.*)&lt;/th&gt;.*","\\1", My_HTML_String)
  • 我认为它不能正常工作。我不仅对“th”(text_that_I_want_to_get)中的内容感兴趣,而且对 tbody 之后的内容感兴趣(这是巨大的,这就是我没有发布它的原因)......而且有很多表格,例如这些,我在 HTML 中没有他们的位置
  • 你应该发布你想要的输出。目前尚不清楚您要提取什么。

标签: r web-scraping rvest xml2


【解决方案1】:

您需要以下三个 xpath:

xpath1 <- "//td[table[./thead/tr/th/text() = 'stdev']]/preceding-sibling::th"
xpath2 <- "//td[table[./thead/tr/th/text() = 'answers']]/preceding-sibling::th"
xpath3 <- "//td[table[./thead/tr/th/text() = 'Reference']]/preceding-sibling::th"

这些查找位于三种表类型中每一种的根节点的td 节点,然后使用您想要的文本找到前面的th 兄弟节点。

因此,要为表类型 1 获取“text_that_I_want_to_get”,您可以:

read_html(url) %>% html_nodes(xpath = xpath1) %>% html_text()
#> [1] "text_that_I_want_to_get"

您可以对xpath2xpath3 执行相同的操作,以从表类型2 和表类型3 中获取文本。

【讨论】:

  • 我的目标其实是获取“th”里面的文字(text_that_I_want_to_get),所以我不能在xpath1里面写。除此之外,每种类型的表都需要分开。例如,第一次,我将只获取所有类型 1 的表。
  • @polo 在这种情况下,这与我在stackoverflow.com/questions/62390373/… 回答的您的其他问题有什么不同,除非您在 xpath 中使用@class = 'string'
  • 不一样,因为当时我必须手动将“type1”、“type2”和“type3”类添加到我的 HTML 中。我可以添加类,因为“th”中的内容在每种类型中都不同(type1 的名称、平均值、stdev;type2 的名称、答案;type3 的参考)。我的目标不是手动打开 HTML 并更正 R 中的所有内容
  • @polo 那么您是否需要代码来识别您正在处理的表格类型并在表格标签中插入class = "type1"class = "type 2" 等?
  • 是的,考虑到“th”,它可以插入类“type1”或“type2”或“type3”(type1 的名称、平均值、stdev;type2 的名称、答案;type3 的参考) .或者它可以考虑以下“th”(名称,意思,type1的stdev;名称,type2的答案;type3的参考)得到“th”(text_that_I_want_to_get)
猜你喜欢
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
  • 1970-01-01
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多