问题描述
我正在抓取并遇到麻烦,使"th"标记的元素出现在另一个包含"type2"类的"th"元素之前.我更喜欢通过在类"type2"的"th"之前确定它是"th"元素,因为我的HTML有很多"th",这是我在表之间发现的唯一区别.
I'm scraping and having trouble getting the element of the "th" tag that comes before the other "th" element that contains the "type2" class. I prefer to take it by identifying that it is the element "th" before the "th" with class "type2" because my HTML has a lot of "th" and that was the only difference I found between the tables.
使用rvest或xml2(或其他R包),我可以得到这个父对象吗?我想要的内容是"text_that_I_want".
Using rvest or xml2 (or other R package), can I get this parent?The content which I want is "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>
推荐答案
相对于给定节点导航xpath的正式且更具通用性的方法是通过 ancestor
preceding-sibling
:
The formal and more generalizable way to navigate xpath relative to a given node is via ancestor
preceding-sibling
:
read_html(htmldoc) %>%
html_nodes(xpath = "//th[@class = 'string type2']/ancestor::td/preceding-sibling::th") %>%
html_text()
#> [1] "text_that_I_want"
这篇关于如何获取某个类之前的HTML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!