zh
English
Español
Tiếng Việt
Deutsch
Українська
Português
Français
भारतीय
Türkçe
한국인
Italiano
Gaeilge
اردو
Indonesia
Polski Web scraping airbnb python 和 scraping Airbnb 数据对于分析房地产市场、研究租金价格动态、进行竞争分析以及评估评论和评级至关重要。这可以通过刮擦技术来实现。然而,访问这些信息可能具有挑战性,因为刮擦可能违反网站的使用条款。
接下来,我们将逐步介绍如何使用 Python 和 Selenium 开发网络搜索器来搜索 airbnb 房源。本指南还将介绍如何避免平台可能施加的阻塞和限制。
创建网页抓取工具的第一步是了解如何访问您感兴趣的网页,因为网站的结构经常会发生变化。要熟悉网站的结构,可以使用浏览器的开发工具来检查网页的 HTML。
要访问 "开发工具",请右键单击网页并选择 "检查 "或使用快捷方式:
每个列表容器都包裹在一个 div 元素中,该元素具有以下属性:class="g1qv1ctd"。
点击 "地点 "并输入 "英国伦敦",我们就可以访问伦敦提供的地点。网站建议添加入住和退房日期。这样就可以计算出房间的价格。
该页面的 URL 将如下所示:
url = "https://www.airbnb.com/s/London--United-Kingdom/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&flexible_trip_lengths%5B%5D=one_week&monthly_start_date=2024-01-01&monthly_length=3&price_filter_input_type=0&channel=EXPLORE&query=London%2C%20United%20Kingdom&place_id=ChIJdd4hrwug2EcRmSrV3Vo6llI&date_picker_type=calendar&source=structured_search_input_header&search_type=autocomplete_click"
从搜索页面,我们将从 Airbnb 抓取产品列表数据的以下属性:
要开始 Web scraping airbnb python 数据,首先需要设置开发环境。具体步骤如下:
虚拟环境允许你隔离不同项目的 Python 软件包及其依赖关系。在不存在跨项目干扰的情况下,每个项目的依赖关系都能保证准确无误。
Windows 用户可以以管理员权限打开命令提示符并运行该命令,创建名为 "venv "的虚拟环境:
python -m venv venv
要激活新创建的虚拟环境,请运行命令:
venv\Scripts\activate
打开终端,执行下面的命令,建立一个名为 "venv "的新虚拟环境:
sudo python3 -m venv venv
激活虚拟环境:
source venv/bin/activate
要停用虚拟环境,只需运行以下命令:
deactivate
现在,您已经建立了虚拟环境,可以安装必要的库。
在已激活的虚拟环境中,运行以下命令安装所需的库:
pip install selenium beautifulsoup4 lxml seleniumwire
Selenium 需要一个驱动程序来连接所选浏览器。本指南将使用 Chrome 浏览器。不过,请确保已为所选浏览器安装了相应的 WebDriver。
下载完成后,确保将驱动程序放在系统 PATH 环境变量可访问的目录中。这将允许 Selenium 找到驱动程序并控制浏览器。
如上所述,首先要做的是在 Python 文件中导入 Seleniumwire 和 BeautifulSoup 库。看起来是这样的
from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time
import csv
import random
我们还将为各种实用程序导入 `random`、`time` 和 `csv` 库。
接下来,我们定义一个代理列表,以避免被 Airbnb 屏蔽。在没有高级代理的情况下尝试发送请求时,您可能会收到 "拒绝访问 "的回复。
设置代理的方法如下:
# 代理人名单
proxies = [
"username:password@Your_proxy_IP_Address:Your_proxy_port1",
"username:password@Your_proxy_IP_Address:Your_proxy_port2",
"username:password@Your_proxy_IP_Address:Your_proxy_port3",
"username:password@Your_proxy_IP_Address:Your_proxy_port4",
"username:password@Your_proxy_IP_Address:Your_proxy_port5",
]
确保将 "YourproxyIPAddress"(您的代理 IP 地址)和 "Yourproxy_port"(您的代理端口)字段自定义为 Proxy-seller 提供的代理地址的相应信息模数。此外,不要忘记将占位符 "用户名 "和 "密码 "改为您的实际凭据。
轮流使用代理服务器是网络搜刮的重要步骤。当网站收到来自同一 IP 地址的多个请求时,通常会阻止或限制机器人和搜索器的访问。通过轮流使用不同的代理 IP 地址,你可以避免被发现,以多个有机用户的身份出现,并绕过网站上实施的大多数反搜刮措施。
要设置旋转,请导入 "随机 "库。我们还定义了一个函数 `get_proxy()`,用于从列表中选择一个代理。该函数使用 random.choice() 方法从代理列表中随机选择一个项目。
def get_proxy():
return random.choice(proxies)
接下来,我们定义名为 "listings() "的主函数。这就是我们要设置 "ChromeDriver "的地方。该函数使用 Selenium 浏览房产列表页面,等待页面加载,并使用 Beautiful Soup 解析 HTML。
def listings(url):
proxy = get_proxy()
proxy_options = {
"proxy": {
"http": f"http://{proxy}",
"https": f"http://{proxy}",
"no_proxy": "localhost,127.0.0.1",
}
}
chrome_options = Options()
chrome_options.add_argument("--headless")
s = Service(
"C:/Path_To_Your_WebDriver"
) # 替换为 ChromeDriver 的路径
driver = webdriver.Chrome(
service=s, seleniumwire_options=proxy_options, chrome_options=chrome_options
)
driver.get(url)
time.sleep(8) # 根据网站加载时间进行调整
soup = BeautifulSoup(driver.page_source, "lxml")
driver.quit()
要使用 Python 对 Airbnb 进行刮擦,我们首先要选择一个随机代理并设置选项。这些选项将用于配置 webdriver。接下来,我们设置 Chrome 浏览器选项。添加 --headless 参数以在无头模式下运行浏览器,这意味着浏览器将在后台运行,没有图形用户界面。
然后使用服务、seleniumwire 选项和 Chrome 选项初始化 webdriver。然后使用 Webdriver 浏览给定的 URL。我们会添加 8 秒钟的休眠时间,让页面完全加载,然后使用 Beautiful Soup 解析返回的 HTML。解析完成后,它会关闭 Webdriver。
成功获取 HTML 内容后,下一步就是提取每个属性的相关数据。使用 BeautifulSoup,我们可以轻松浏览结构,找到包含必要信息的部分。
首先,我们要确定页面上所有保存属性详细信息的区块。这些部分包括 URL、标题、描述、评级、价格和任何其他信息。
listing_elements = soup.find_all("div", class_="g1qv1ctd")
for listing_element in listing_elements:
这段代码使用 BeautifulSoup 的 find_all()方法查找所有类名为 "g1qv1ctd "的 div 标签。每一个标签都代表 Airbnb 页面上的一处房产。然后,代码会循环浏览这些标签,以收集相关数据。
对于找到的每个区块,我们都会提取 URL。
URL_element = soup.find("a", class_="rfexzly")
listing_data["Listing URL"] = (
"https://www.airbnb.com" + URL_element["href"] if URL_element else ""
)
我们在汤对象中搜索锚标签类 "rfexzly"。如果找到,就会提取 "href "属性(其中包含相对 URL),并将其与基本 URL 结合,创建完整地址。如果未找到,则使用空字符串以避免出错。
接下来,我们抓取标题,它位于一个类名为 "t1jojoys "的 div 标签内。我们检索并清理文本。如果标签不存在,我们只需存储一个空字符串。
title_element = listing_element.find("div", class_="t1jojoys")
listing_data["Title"] = (
title_element.get_text(strip=True) if title_element else ""
)
Description_element = listing_element.find("span", class_="t6mzqp7")
listing_data["Description"] = (
Description_element.get_text(strip=True) if Description_element else ""
)
与获取标题的方法类似,这部分也会找到一个类名为 "t6mzqp7 "的 span 标签。我们提取并清理文本内容,其中包含对属性的简短描述。
rating_element = listing_element.find("span", class_="ru0q88m")
listing_data["Rating"] = (
rating_element.get_text(strip=True) if rating_element else ""
)
如上面的代码所示,一个类名为 "ru0q88m "的 span 标签保存了评级值。我们对其进行提取和清理,删除多余的空格。
最后,我们提取价格。
price_element = listing_element.select_one("._1y74zjx")
listing_data["Price"] = (
f"{price_element.get_text(strip=True)} per night" if price_element else ""
)
这段代码会在当前列表元素中查找类别为"_1y74zjx "的元素。如果找到了这个通常包含价格信息的元素,就会提取、清理其文本内容,并添加 "每晚",以形成一个更翔实的价格字符串。
某些属性可能包含额外的详细信息。
listing_info_element = listing_element.find("span", {"aria-hidden": "true"})
listing_data["Additional Listing information"] = (
listing_info_element.get_text(strip=True) if listing_info_element else ""
)
我们搜索带有 aria-hidden="true" 属性的 span 标签来查找这些额外信息。从单个属性中收集所有相关数据后,我们将其添加到列表中:
listings.append(listing_data)
处理完所有列表后,我们会返回列表,每个列表都是一个包含提取数据的字典。
return listings
在成功从 Airbnb 页面上获取数据后,下一个重要步骤就是存储这些宝贵的信息,以供将来分析和参考。我们使用 csv 库来完成这项任务。我们以写入模式打开一个 CSV 文件,并创建一个 csv.DictWriter 对象。然后,我们将文件头和数据写入文件。
airbnb_listings = listings(url)
csv_file_path = "proxy_web_listings_output.csv"
with open(csv_file_path, "w", encoding="utf-8", newline="") as csv_file:
fieldnames = [
"Listing URL",
"Title",
"Description",
"Rating",
"Price",
"Additional Listing information",
]
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
for listing in airbnb_listings:
writer.writerow(listing)
print(f"Data has been exported to {csv_file_path}")
以下是本教程中使用的完整 Python 代码,用于搜索 Airbnb:
from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time
import csv
import random
# 代理人名单
proxies = [
"username:password@Your_proxy_IP_Address:Your_proxy_port1",
"username:password@Your_proxy_IP_Address:Your_proxy_port2",
"username:password@Your_proxy_IP_Address:Your_proxy_port3",
"username:password@Your_proxy_IP_Address:Your_proxy_port4",
"username:password@Your_proxy_IP_Address:Your_proxy_port5",
]
def get_proxy():
return random.choice(proxies)
def listings(url):
proxy = get_proxy()
proxy_options = {
"proxy": {
"http": f"http://{proxy}",
"https": f"http://{proxy}",
"no_proxy": "localhost,127.0.0.1",
}
}
chrome_options = Options()
chrome_options.add_argument("--headless")
s = Service(
"C:/Path_To_Your_WebDriver"
) # 替换为 ChromeDriver 的路径
driver = webdriver.Chrome(
service=s, seleniumwire_options=proxy_options, chrome_options=chrome_options
)
driver.get(url)
time.sleep(8) # 根据网站加载时间进行调整
soup = BeautifulSoup(driver.page_source, "lxml")
driver.quit()
listings = []
# 查找页面上的所有列表元素
listing_elements = soup.find_all("div", class_="g1qv1ctd")
for listing_element in listing_elements:
# 从每个列表元素中提取数据
listing_data = {}
# 上市网址
URL_element = soup.find("a", class_="rfexzly")
listing_data["Listing URL"] = (
"https://www.airbnb.com" + URL_element["href"] if URL_element else ""
)
# 标题
title_element = listing_element.find("div", class_="t1jojoys")
listing_data["Title"] = (
title_element.get_text(strip=True) if title_element else ""
)
# 说明
Description_element = listing_element.find("span", class_="t6mzqp7")
listing_data["Description"] = (
Description_element.get_text(strip=True) if Description_element else ""
)
# 评级
rating_element = listing_element.find("span", class_="ru0q88m")
listing_data["Rating"] = (
rating_element.get_text(strip=True) if rating_element else ""
)
# 价格
price_element = listing_element.select_one("._1y74zjx")
listing_data["Price"] = (
f"{price_element.get_text(strip=True)} per night" if price_element else ""
)
# 其他上市信息
listing_info_element = listing_element.find("span", {"aria-hidden": "true"})
listing_data["Additional Listing information"] = (
listing_info_element.get_text(strip=True) if listing_info_element else ""
)
# 将列表数据添加到列表中
listings.append(listing_data)
return listings
url = "https://www.airbnb.com/s/London--United-Kingdom/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&flexible_trip_lengths%5B%5D=one_week&monthly_start_date=2024-01-01&monthly_length=3&price_filter_input_type=0&channel=EXPLORE&query=London%2C%20United%20Kingdom&place_id=ChIJdd4hrwug2EcRmSrV3Vo6llI&date_picker_type=calendar&source=structured_search_input_header&search_type=autocomplete_click"
airbnb_listings = listings(url)
csv_file_path = "proxy_web_listings_output.csv"
with open(csv_file_path, "w", encoding="utf-8", newline="") as csv_file:
fieldnames = [
"Listing URL",
"Title",
"Description",
"Rating",
"Price",
"Additional Listing information",
]
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
for listing in airbnb_listings:
writer.writerow(listing)
print(f"Data has been exported to {csv_file_path}")
该代码段保证将刮擦器收集到的任何数据以 CSV 格式保存在名为 "proxyweblistings_output.csv "的文件中。
我们的搜索结果会保存到一个名为 "proxy_web_listings_output.csv "的 CSV 文件中,如下所示。
本指南有效解释了如何使用 Python 搜刮 Airbnb 数据列表,从而提取价格、可用性和评论等关键细节。它强调了使用代理和轮换代理的重要性,以防止被 Airbnb 的反僵尸措施拦截。
利用 python 和 Selenium 抓取 Airbnb 数据,你可以直接获取有价值的信息,如价格、可用性等,这些都是市场调研、投资分析,甚至是构建自己的房地产工具的关键信息。虽然这个过程会遇到技术挑战(以及一些法律上的灰色地带),但设置正确的环境、了解网站如何运行以及使用代理和无头浏览器等工具可以帮助你绕过大多数障碍。但请务必遵守平台的使用条款,并始终以负责任的态度处理数据。
评论: 0