【问题标题】:Trouble selecting correct css elements for scraping with rvest无法选择正确的 css 元素以使用 rvest 进行抓取
【发布时间】:2023-03-14 05:40:02
【问题描述】:

目标:我正在尝试从篮球参考网站上抓取 NBA 球队的输赢记录。

更广泛地说,我试图更好地了解如何正确使用 CSS 选择器小工具从网站上抓取指定元素,但希望能找到解决此问题的方法。

我正在使用的网址 (https://www.basketball-reference.com/leagues/NBA_2018_standings.html) 上有多个表格,所以我尝试使用 CSS 选择器小工具来指定我想要的元素,即“扩展排名”表格 - 大约 1/页面下方的 3 条。

我已经阅读了有关网络抓取的各种教程,其中涉及 rvestdplyr 包,以及 CSS 选择器网络浏览器插件(我已将其安装在我选择的浏览器 Chrome 中)。这就是我想要的。

到目前为止,这是我的代码:

url <- "https://www.basketball-reference.com/leagues/NBA_2018_standings.html"
css <- "#expanded_standings"

url %>%
  read_html() %>%
  html_nodes(css) %>%
  html_table()

这段代码的结果是错误:

Error: html_name(x) == "table" is not TRUE

当我删除最后一行代码时,我得到:

url %>%
  read_html() %>%
  html_nodes(css)

{xml_nodeset (0)}

我定义 CSS 对象的方式/我使用 CSS 选择器工具的方式似乎存在问题。我一直在做的是单击所需表格的最右边缘,以便表格周围有一个矩形。

我还尝试单击表格中的特定“单元格”(即“65-17”,这是休斯顿火箭队行的“总体”列中的值),但这似乎突出了一些,但不是所有表格,以及网页上其他表格的随机部分。

谁能提供解决方案?如果你能帮助我理解我在哪里/为什么我在做什么是不正确的,那就加分。

提前致谢!

【问题讨论】:

  • 试试css &lt;- "#confs_standings_E" 看看是不是你想要的。我不觉得那个工具有用,检查效果很好。
  • 在“会议排名”部分选择页面上的第一个表格。我正在尝试在页面下方选择一个表格,“扩展排名”。不过感谢您的帮助!

标签: r web-scraping css-selectors rvest


【解决方案1】:
library(rvest)
library(dplR)
library(stringr)
library(magrittr)

url <- "https://www.basketball-reference.com/leagues/NBA_2018_standings.html"
css <- "#expanded_standings"
css <- "#all_expanded_standings"

webpage <- read_html(url)
print(webpage)
mynode <- html_nodes(webpage,css)

mystr <- toString(mynode)
mystr <- gsub("<!--","",mystr)
mystr <- gsub("-->","",mystr)

newdiv <- read_html(mystr)

newtable <- html_nodes(newdiv,"#expanded_standings")
newframe <- html_table(newtable)

print(newframe)

【讨论】:

  • 看起来有点老套,但是获取那个 div,替换评论标记,重新制作 html,获取 id=#expanded_standings 的表格并创建框架数据。
  • Hacky 确实,但这完成了工作。谢谢你帮我解决这个问题!似乎 url 定义表格的方式有点不稳定,因此这种“hacky”解决方法。感谢您的帮助!
【解决方案2】:
library(rvest)
library(dplR)
library(stringr)
library(magrittr)

url <- "https://www.basketball-reference.com/leagues/NBA_2018_standings.html"
css <- "#expanded_standings"
css <- "#all_expanded_standings"

webpage <- read_html(url)
print(webpage)
mynode <- html_nodes(webpage,css)
#print node to console - interprets slashes
cat(toString(mynode))

【讨论】:

  • 我仍然对这种 r 语言感兴趣。 - 第一天。该代码使用注释块中的表数据获取 div。 30 行数据。
  • 这很有帮助,让我更接近解决方案,但我不确定它是否一直存在。当我用“#all_expanded_standings”定义css元素时,它确实返回了一个html节点,但是当我将它传递给html_table时,它不起作用(错误:html_name(x)==“table”不是TRUE) .由于#all_expanded_standings css 元素似乎是一个表格包装器而不是一个实际的表格,因此它不会通过 html_table() 函数成功传递。
【解决方案3】:

我尝试下载裸 url html(在 javascript 渲染之前)。看起来很奇怪,就像表格数据在注释块中一样。在这个 div 中 - 有“扩展排名”表。

我使用python和beautifulsoup提取元素,然后删除注释标记,resoup字符串部分,然后将字符串解析为td位。奇怪的是排名在第一个元素中。

【讨论】:

  • div 有 id="all_expanded_standings"(我的标记被论坛软件破坏了)
  • 嗯,我不确定我是否完全理解该解决方案。我刚刚尝试使用“all_expanded_standings”作为 html 节点,但这也不起作用 - 仍然返回一个空列表。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 2021-09-25
  • 2021-10-08
  • 1970-01-01
  • 2021-03-19
  • 2021-04-07
  • 2021-04-18
相关资源
最近更新 更多