【问题标题】:How can I scrape the title from a class with RVEST?如何使用 RVEST 从课程中刮取标题?
【发布时间】:2019-10-09 02:56:56
【问题描述】:

我想从墨西哥零售网页上抓取所有智能手机的名称。

我不知道为什么我的代码不起作用,因为我已经为类似的网页做过这个,显然 RVEST 没有“读取” html 代码的“类”。

使用 Google 选择器小工具,我发现智能手机名称在一个名为“.name”的类中,所以我尝试了这个:

url <- 'https://www.chedraui.com.mx/Departamentos/Tecnolog%C3%ADa/Telefon%C3%ADa/Celular/c/MC230202?siteName=Sitio+de+Chedraui&isAlcoholRestricted=false'
web <- read_html(url)

web %>%
  html_nodes('.name') %>%
  html_text()

但是结果是:''''

预期的结果是一个包含所有智能手机名称的向量。

【问题讨论】:

  • 似乎这些节点是用javascript动态创建的。如果您只运行web %&gt;% html_nodes(".name") 部分,您会发现您没有这些产品的节点,因此没有任何东西可以从中提取文本。关于使用 RSelenium 或其他有助于抓取动态页面的工具有很多问题
  • 请花点时间接受过去的答案,如果它们有效,因为它有利于网站。您可以使用以下资源查看其工作原理:stackoverflow.com/help/someone-answers
  • @camile 谢谢,我会试试 RSelenium :D
  • @QHarr 会做的:)

标签: r web-scraping screen-scraping rvest


【解决方案1】:

检查响应,您将看到不同类别下的信息

library(rvest)
page <- read_html("https://www.chedraui.com.mx/Departamentos/Tecnolog%C3%ADa/Telefon%C3%ADa/Celular/c/MC230202?siteName=Sitio+de+Chedraui&isAlcoholRestricted=false")
titles <- page %>% 
  html_nodes('.product__list--thumb') %>%
  html_attr(., "title")

【讨论】:

  • 但是,你怎么知道 ".product__list" 的 "thumb" 类会起作用?因为我检查了 html 代码,但每个智能手机的所有功能都在
  • 我检查了返回的实际 html
  • 你是怎么做到的?,我检查东西的方式是点击按钮和“检查”
  • 我使用rvest导出html返回文本文件示例:stackoverflow.com/questions/37631226/…,google.com/…
  • 我也倾向于使用这个工具来查看 xhr 可能返回的内容:try.jsoup.org
  • 【解决方案2】:

    要查找您的 HTML 文本属于哪个类而不与网页结构交互,即不使用网页上的“检查”,您可以使用 CSS 选择器搜索 HTML 文本,然后使用 xml2::xml_attrs() 访问它所属的类.

    这是一个使用“华为”作为文本的示例,它出现在您的一个标题中。

    "https://www.chedraui.com.mx/Departamentos/Tecnolog%C3%ADa/Telefon%C3%ADa/Celular/c/MC230202?siteName=Sitio+de+Chedraui&isAlcoholRestricted=false" %>% 
      read_html() %>% 
      html_nodes(":contains('Huawei')") %>% # search for string. Note the separate types of quotations
      xml2::xml_attrs() %>% # show all the attributes the string belongs to
      purrr::map("class") %>% # pull just 'class' attrs from the list
      unlist %>% unique
    

    您还可以使用通配符来搜索字符串,例如将html_nodes(":contains('Huawei')") 替换为html_nodes("*:contains('Huaw')")

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签