Yelp餐厅信息网络抓取(运行循环以获取多个餐厅信息时遇到错误)

时间:2019-06-18 00:24:13

标签: r web-scraping

尝试从Yelp网站抓取餐厅信息,例如价格范围($$$$),价格说明,酒水,电话,网站,健康评分。该代码在2家餐厅-Dirty French和Uncle Boons上都可以正常使用,但是在餐厅Legacy Records使用相同的代码时,它开始显示错误。这是因为我在酒类代码(和代码中未显示的网站)中使用的XPath对于“肮脏的法国人”和“伯恩斯叔叔”以及“传统记录”而言是不同的。此外,旧记录没有价格范围,但仍会显示在输出中。

即使XPath保持不变,是否有任何方法可以遍历不同的餐厅并获得所需的信息,或者无论如何,每个餐厅的XPath都会发生变化?我正在为1000多家餐厅收集数据,因此无法考虑每次手动更改代码。

我什至朝着正确的方向前进吗?有更好的方法吗?

此代码可以很好地在您的系统中复制。

actual_name <- data.frame(actual_name = c("dirty-french-new-york", "uncle- 
boons-new-york", 
                                      "legacy-records-new-york"))


titles <- c()
urls <- c()

urls <- paste(initial, actual_name$actual_name, sep = "")

map_df(urls, function(i){
  url <- read_html(i)

  data.frame(Title = url %>% html_node("title") %>% html_text(),
         HealthScore = url %>% html_node(".health-score-description") %>% 
html_text(), 
         Rating = url %>%
           html_node(xpath = "//*   [@id='wrap']/div[2]/div/div[1]/div/div[3]/div[1]/div[2]/div[1]/div[1]/div") 
%>%
           html_attr("title"),
         Phone = url %>% html_node(".biz-phone") %>% html_text(),
         Price = url %>% html_node(".price-range") %>% html_text(),
         PriceDescription = url %>% html_node(".price-description") %>% 
html_text(),
         Alcohol = url %>%
           html_nodes(xpath = "//* [@id='wrap']/div[2]/div/div[1]/div/div[4]/div[1]/div/div[2]/ul/li[3]/span[2]/a") %>%
           html_text())
}) -> titles

0 个答案:

没有答案