我正在使用 R 從網頁中抓取表格。我的問題是網頁上的表格列之一在這兩個名稱之間隨機更改其標題名稱:“住宿型別”和“房間型別”。
因此,如果我不希望 R 腳本在到達特定代碼行時中斷,我需要手動檢查網頁并相應地更正我的 R 代碼。
這是代碼(當該列標題為“住宿型別”時):
output31 <- output3 %>% mutate_at(c("Accommodation Type", "Price for 1 week"), ~str_extract(., ".*\n"))
這是代碼(當該列標題為“房間型別”時):
output31 <- output3 %>% mutate_at(c("Room type", "Price for 1 week"), ~str_extract(., ".*\n"))
有沒有辦法插入一種帶有邏輯的 IF 條件,如果它找到“住宿型別”作為列標題,那么它必須忽略提到“房間型別”的那行代碼,反之亦然?
編輯(添加完整代碼):
library(rvest)
library(dplyr)
library(stringr)
if (!require(tables)) install.packages('tables')
library(tables)
library(xlsx)
url3 <- read_html("https://www.booking.com/hotel/mu/lux-grand-baie-resort-amp-residences.en-gb.html?aid=356980&label=gog235jc-1DCAsonQFCE2hlcml0YWdlLWF3YWxpLWdvbGZIM1gDaJ0BiAEBmAExuAEXyAEM2AED6AEB-AECiAIBqAIDuAKiwqmEBsACAdICJGFkMTQ3OGU4LTUwZDMtNGQ5ZS1hYzAxLTc0OTIyYTRiZDIxM9gCBOACAQ&sid=729aafddc363c28a2c2c7379d7685d87&all_sr_blocks=36363601_246990918_2_85_0&checkin=2021-12-08&checkout=2021-12-15&dest_id=-1354779&dest_type=city&dist=0&from_beach_key_ufi_sr=1&group_adults=2&group_children=0&hapos=1&highlighted_blocks=36363601_246990918_2_85_0&hp_group_set=0&hpos=1&no_rooms=1&sb_price_type=total&sr_order=popularity&sr_pri_blocks=36363601_246990918_2_85_0__29200&srepoch=1619681695&srpvid=51c8354f03be0097&type=total&ucfs=1&req_children=0&req_adults=2&hp_refreshed_with_new_dates=1")
output3 <- url3 %>%
html_nodes(xpath = './/table[@id="hprt-table"]') %>%
html_table() %>% .[[1]]
output31 <- output3 %>% mutate_at(c("Accommodation Type", "Price for 1 week"), ~str_extract(., ".*\n"))
uj5u.com熱心網友回復:
您可以創建一個函式來處理清理作業或在腳本中使用函式內部的邏輯。
該函式檢查“房間型別”是否在列名中。如果是,用第一行代碼清理,如果不是,用 else 部分清理。
clean_up <- function(data){
if("Room type" %in% colnames(data)){
out <- data %>%
mutate_at(c("Room type", "Price for 1 week"), ~str_extract(., ".*\n"))
} else {
out <- data %>%
mutate_at(c("Accommodation Type", "Price for 1 week"), ~str_extract(., ".*\n"))
}
out
}
output31 <- clean_up(output3)
請注意,您可能違反了 booking.com 的 TOS
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/362045.html
上一篇:網路從商業報紙上抓取鏈接
