rvest如何通过ID选择特定的CSS节点 [英] rvest how to select a specific css node by id

查看:202
本文介绍了rvest如何通过ID选择特定的CSS节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用rvest软件包从网页中抓取数据。 html代码采用一种简单的格式,如下所示:

I'm trying to use the rvest package to scrape data from a web page. In a simple format, the html code looks like this:

<div class="style">
   <input id="a" value="123">
   <input id="b">
</div>

我想从第一个输入中获取值123。我尝试了以下R代码:

I want to get the value 123 from the first input. I tried the following R code:

library(rvest)
url<-"xxx"
output<-html_nodes(url, ".style input")

这将返回输入标签列表:

This will return a list of input tags:

[[1]]
<input id="a" value="123">
[[2]]
<input id="b">

接下来,我尝试使用html_node通过id引用第一个输入标签:

Next I tried using html_node to reference the first input tag by id:

html_node(output, "#a")

此处返回的是空值列表,而不是我想要的输入标签。

Here it returned a list of nulls instead of the input tag I want.

[[1]]
NULL
[[2]]
NULL

我的问题是,如何使用其ID引用输入标签?

My question is, how can I reference the input tag using its id?

推荐答案

您可以使用xpath:

You can use xpath:

require(rvest)
text <- '<div class="style">
   <input id="a" value="123">
   <input id="b">
</div>'

h <- read_html(text)

h %>% 
  html_nodes(xpath = '//*[@id="a"]') %>%
  xml_attr("value")

获取css-和xpath-selector的最简单方法是使用

The easiest way to get css- and xpath-selector is to use http://selectorgadget.com/. For a specific attribute like yours use chrome's developer toolbar to get the xpath as follows:

这篇关于rvest如何通过ID选择特定的CSS节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆