我正在从 booking.com 的一个页面上抓取并创建数据框我注意到并不是所有的酒店都有评级。
我试过这个例如:
# Got the elements from Inspect code of the page
titles_page <- page %>% html_elements("div[data-testid='title'][class='fcab3ed991 a23c043802']") %>% html_text()
prices_page <- page %>% html_elements("span[data-testid='price-and-discounted-price']") %>% html_text()
ratings_page <- page %>% html_elements("div[aria-label^='Punteggio di']") %>% html_text()
# The variable ratings
tryCatch(expr ={
ratings_page <- remDr$findElements(using = "xpath", value = "div[aria-label^='Punteggio di']")$getElementAttribute('value')
},
#If the information does not exist in this way it writes NA to the ratings element
error = function(e){
ratings_page <-NA
})
它并没有改变任何东西。
如何在对象没有价值的情况下报告NA?
这是一个基于此链接策略的解决方案:如何将项目拼凑在一起,以免丢失索引?.
这里的关键是使用
html_element()
(没有s)。 html_element()
将始终返回答案,即使它是 NA。这样,如果元素在父节点中丢失,NA 将填补空白。
library(rvest)
library(dplyr)
#read the page
url <-"https://www.booking.com/searchresults.it.html?ss=Firenze%2C+Toscana%2C+Italia&efdco=1&label=booking-name-L*Xf2U1sq4*GEkIwcLOALQS267777916051%3Apl%3Ata%3Ap1%3Ap22%2C563%2C000%3Aac%3Aap%3Aneg%3Afi%3Atikwd-65526620%3Alp9069992%3Ali%3Adec%3Adm%3Appccp&aid=376363&lang=it&sb=1&src_elem=sb&src=index&dest_id=-117543&dest_type=city&ac_position=0&ac_click_type=b&ac_langcode=it&ac_suggestion_list_length=5&search_selected=true&search_pageview_id=2e375b14ad810329&ac_meta=GhAyZTM3NWIxNGFkODEwMzI5IAAoATICaXQ6BGZpcmVAAEoAUAA%3D&checkin=2023-06-11&checkout=2023-06-18&group_adults=2&no_rooms=1&group_children=0&sb_travel_purpose=leisure&fbclid=IwAR1BGskP8uicO9nlm5aW7U1A9eABbSwhMNNeQ0gQ-PNoRkHP859L7u0fIsE"
page <- read_html(url)
#parse out the parent node for each parent
properties <- html_elements(page, xpath=".//div[@data-testid='property-card']")
#now find the information from each parent
#notice html_element - no "s"
title <- properties %>% html_element("div[data-testid='title']") %>% html_text()
prices <- properties %>% html_element("span[data-testid='price-and-discounted-price']") %>% html_text()
ratings <- properties %>% html_element(xpath=".//div[@aria-label]") %>% html_text()
data.frame(title, prices, ratings)
title prices ratings
1 Sweetly home in Florence US$1.918 <NA>
2 Pepi Red US$3.062
3 hu Firenze Camping in Town US$902 8,4
4 Plus Florence US$1.754 7,9
5 Artemente Florence B&B US$4.276
6 Villa Aruch US$1.658
7 Hotel Berna US$2.184
8 Hotel Gioia US$2.437
9 Hotel Magenta US$3.250
10 Villa Neroli US$3.242
11 Residenza Florentia US$2.792 8,0
12 Ridolfi Sei Suite Florence US$1.243 <NA>
...
也许像下面这样。未经测试。
# The variable ratings
ratings_page <- tryCatch(
expr = {
elem <- remDr$findElements(using = "xpath", value = "div[aria-label^='Punteggio di']")
elem$getElementAttribute('value')
},
# If the information does not exist in this way it writes NA to the ratings element
error = function(e) NA
)