首页 > 解决方案 > 如何从网站上抓取数据并在 R 中以指定格式写入 csv?

问题描述

我正在尝试从https://www.booking.com/country.html抓取数据。

这个想法是提取有关为特定国家列出的任何类型的住宿的所有数字。

输出需要在 Excel 文件的“A 列”中列出所有国家/地区的列表,以及每个国家/地区与国家名称相邻的不同物业类型(例如公寓、旅馆、度假村等)的相关列表数量在单独的列中。

我需要捕获给定国家/地区所有属性类型的所有详细信息。

下图描述了所需的输出格式。

上图描述了 Excel 中所需的输出格式。我可以使用以下代码获取国家/地区,但不能使用属性类型及其各自的数据。

如何以迭代方式获取所有国家/地区的数据并写入 csv。

library(rvest)
library(reshape2)
library(stringr)

url <- "https://www.booking.com/country.html"

bookingdata <- read_html(url)

#extracting the country
country <- html_nodes(bookingdata, "h2 > a") %>% 
  html_text()
write.csv(country, 'D:\\web scraping\\country.csv' ,row.names = FALSE)
print(country)

#extracting the data inside the inner div 
html_nodes(bookingdata, "div >div > div > ul > li > a")%>%
  html_text()
for (i in country) {
print(i)
html_nodes(pg, "ul > li > a") %>% 
  html_text()
  print(accomodation)
}

#getting all the data
accomodation <- html_nodes(pg, "ul > li > a") %>% 
  html_text()

#separating the numbers
accomodation.num <- (str_extract(accomodation, "[0-9]+"))
#separating the characters
accomodation.char <- (str_extract(accomodation,"[aA-zZ]+"))
#separating unique characters
unique(accomodation.char)

标签: pythonrexcelweb-scrapingbooking.com-api

解决方案


import requests
from bs4 import BeautifulSoup
import pandas as pd

r = requests.get('https://www.booking.com/country.html')
soup = BeautifulSoup(r.text, 'html.parser')

data = []
for item in soup.findAll('div', attrs={'class': 'block_third block_third--flag-module'}):
    country = [(country.text).replace('\n', '')
               for country in item.findAll('a')]
    data.append(country)

final = []
for item in data:
    final.append(item)

df = pd.DataFrame(final)
df.to_csv('output.csv')

在线查看输出:点击这里

在此处输入图像描述

通过 CHAT 满足用户需求的另一个版本:

import requests
from bs4 import BeautifulSoup
import pandas as pd

r = requests.get('https://www.booking.com/country.html')
soup = BeautifulSoup(r.text, 'html.parser')

data = []
for item in soup.select('div.block_third.block_third--flag-module'):
    country = [(country.text).replace('\n', '')
               for country in item.select('a')]
    data.append(country)

final = []
for item in data:
    final.append(item)

df = pd.DataFrame(final).set_index(0)
df.index.name = 'location'
split = df.stack().str.extract('^(?P<freq>[\d,]+)\s+(?P<category>.*)').reset_index(level=1, drop=True)
pvt = split.pivot(columns='category', values='freq')
pvt.sort_index(axis=1, inplace=True)
pvt.reset_index().to_csv('output2.csv', index=False)

推荐阅读