如何使用rvest和xpath抓取表格?

12

使用以下文档,我一直在试图从marketwatch.com上爬取一系列的表格。

下面的代码表示其中一个表:

enter image description here

链接和xpath已经包含在代码中:

url <- "http://www.marketwatch.com/investing/stock/IRS/profile"
valuation <- url %>%
  html() %>%
  html_nodes(xpath='//*[@id="maincontent"]/div[2]/div[1]') %>%
  html_table()
valuation <- valuation[[1]]

我遇到了以下错误:

Warning message:
'html' is deprecated.
Use 'read_html' instead.
See help("Deprecated") 

提前致谢。


4
请将 html() 移除并替换为 read_html() - cory
1
那不是错误,而是警告。你的代码仍然可以在有警告的情况下运行。 - SymbolixAU
1个回答

15

那个网站没有使用HTML表格,所以html_table()找不到任何东西。它实际上使用了divcolumndata lastcolumn

因此,你可以做类似于:

url <- "http://www.marketwatch.com/investing/stock/IRS/profile"
valuation_col <- url %>%
  read_html() %>%
  html_nodes(xpath='//*[@class="column"]')
    
valuation_data <- url %>%
  read_html() %>%
  html_nodes(xpath='//*[@class="data lastcolumn"]')

甚至更多

url %>%
  read_html() %>%
  html_nodes(xpath='//*[@class="section"]')

为了让你更快地达到目标。

请您还要阅读他们的使用条款-尤其是3.4。


你如何找到XPath(有工具可以找到它,你能把它添加到答案中吗?) - userJT
1
右键单击元素并选择“检查”。然后只需阅读HTML即可。 - SymbolixAU

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接