【问题标题】:How can I scrape this recipe?我怎样才能刮掉这个食谱?
【发布时间】:2018-08-29 00:38:42
【问题描述】:

我正在尝试为我自己的个人收藏收集一些食谱。它在某些网站上效果很好,因为网站结构有时很容易允许抓取,但有些更难。这个我不知道怎么处理:

https://www.koket.se/halloumigryta-med-tomat-linser-och-chili

暂时,让我们假设我想要左边的配料。如果我检查网站,看起来我想要的是两个 article class="ingredients" 块。但我似乎无法到达那里。

我从以下开始:

library(rvest)
library(tidyverse)
read_html("https://www.koket.se/halloumigryta-med-tomat-linser-och-chili") %>%
  html_nodes(".recipe-column-wrapper") %>% 
  html_nodes(xpath = '//*[@id="react-recipe-page"]')

但是,运行上述代码显示所有成分都存储在data-item 中,如下所示:

<div id="react-recipe-page" data-item="{
   "chefNames":"<a href='/kockar/siri-barje'>Siri Barje</a>",
   "groupedIngredients":[{
      "header":"Kokosris",
      "ingredients":[{
         "name":"basmatiris","unit":"dl","amount":"3","amount_info":{"from":3},"main":false,"ingredient":true
      }
      <<<and so on>>>

所以我有点困惑,因为从检查网站来看,一切似乎都整齐地放在我可以提取的东西中,但现在不是。相反,我需要一些严肃的正则表达式才能得到我想要的一切。

所以我的问题是:我错过了什么吗?有什么方法可以获取ingredients 文章的内容吗?

(我尝试了 SelectorGadget,但它只给了我No valid path found)。

【问题讨论】:

    标签: r web-scraping rvest


    【解决方案1】:

    您可以使用rvest 包中的html_attr("data-item") 提取属性。

    此外,data-item 属性看起来像是 JSON 格式,您可以使用 jsonlite 包中的 fromJSON 将其转换为列表:

    html <- read_html("https://www.koket.se/halloumigryta-med-tomat-linser-och-chili") %>%
      html_nodes(".recipe-column-wrapper") %>% 
      html_nodes(xpath = '//*[@id="react-recipe-page"]')
    
    recipe <- html %>% html_attr("data-item") %>% 
      fromJSON
    

    最后,recipe 列表包含许多不相关的不同值,但元素 recipe$ingredients 中也有成分和测量值。

    【讨论】:

    • 哇,这比我希望的还要好。谢谢!
    猜你喜欢
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多