我正在嘗試抓取此網頁上表格中的資料(下面 R 代碼中提供的 URL)。
我的 R 代碼確實提取了表格,但我想修剪名為“您的選擇”的列中找到的資訊
我不想要名為“您的選擇”的列中的所有資料。我只想提取第一個“\n”之前的那些文本。
這是我的 R 代碼:
library(tidyverse)
content <- read_html("https://www.booking.com/hotel/mu/tamarin.en-gb.html?aid=356980&label=gog235jc-1DCAsonQFCE2hlcml0YWdlLWF3YWxpLWdvbGZIM1gDaJ0BiAEBmAExuAEXyAEM2AED6AEB-AECiAIBqAIDuAKiwqmEBsACAdICJGFkMTQ3OGU4LTUwZDMtNGQ5ZS1hYzAxLTc0OTIyYTRiZDIxM9gCBOACAQ&sid=729aafddc363c28a2c2c7379d7685d87&all_sr_blocks=36363601_246990918_2_85_0&checkin=2021-11-15&checkout=2021-11-20&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")
tables <- content %>% html_table(fill = TRUE)
View(tables)
second_table <- tables[[2]]
View(second_table)
在 RStudio 中,“您的選擇”列中的資料如下(摘錄顯示):
1 次免費取消\n2021 年 11 月 12 日 23:59 前\n\n\n\n\n\n\n\n\n\n10% 基本費率折扣可用\n\n\n\n\n\n \n膳食:\n此房間不提供膳食選擇。\n\n\n取消:\n\n您可以在抵達前 2 天免費取消。如果您在抵達前 2 天取消預訂,我們將向您收取預訂的總價。如果您沒有出現,我們將向您收取預訂的總價。\n\n\n預付款:\n我們將隨時向您收取總價的預付款。
2 含早餐\n\n\n\n\n\n\n\n\n免費取消\n2021 年 11 月 12 日 23:59 前\n\n\n\n\n\n\n\n\n \n提供 10% 的基本房價折扣\n\n\n\n\n\n\n膳食:\n包括歐陸式早餐\n早餐評分 7.6 - 基于 38 條評論。\n\n\n\n取消:\n\n您可在抵達前 2 天免費取消。如果您在抵達前 2 天取消預訂,我們將向您收取預訂的總價。如果您沒有出現,我們將向您收取預訂的總價。\n\n\n預付款:\n我們將隨時向您收取總價的預付款。
3 含早餐和晚餐\n\n\n\n\n\n\n\n\n\n免費取消\n2021 年 11 月 12 日 23:59 前\n\n\n\n\n\n\n\ n\n\n提供 10% 基本房價折扣\n\n\n\n\n\n\n膳食:\n房價包括半膳。\n早餐評分 7.6 - 基于 38 條評論。\n\n \n\n取消:\n\n您可以在抵達前 2 天免費取消。如果您在抵達前 2 天取消預訂,我們將向您收取預訂的總價。如果您沒有出現,我們將向您收取預訂的總價。\n\n\n預付款:\n我們將隨時向您收取總價的預付款。
為簡化起見,我希望“您的選擇”列如下所示:
Your Choices
FREE cancellation
Good breakfast included
Breakfast & dinner included
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
你可以sub在第一次之后放棄一切"\n"-
library(tidyverse)
library(rvest)
tables <- content %>% html_table(fill = TRUE)
second_table <- tables[[2]]
second_table$`Your choices` <- sub('\n.*', '', second_table$`Your choices`)
second_table$`Your choices`
# [1] "FREE cancellation" "Good breakfast included"
# [3] "Breakfast & dinner included" "All-Inclusive"
# [5] "Breakfast & dinner included" "All-Inclusive"
# [7] "FREE cancellation" "Breakfast & dinner included"
# [9] "Good breakfast included" "All-Inclusive"
#[11] "Breakfast & dinner included" "All-Inclusive"
#[13] "FREE cancellation" "Good breakfast included"
#[15] "Breakfast & dinner included" "All-Inclusive"
#[17] "Breakfast & dinner included" "FREE cancellation"
#[19] "Good breakfast included" "All-Inclusive"
#[21] "Breakfast & dinner included" "All-Inclusive"
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341172.html
