Python 利用BeautifulSoup方法获取贝壳网二手房房源数据
时间: 2024-09-21 20:09:32 浏览: 209
BeautifulSoup是一个Python库,常用于从HTML和XML文档中提取结构化数据。如果你想从贝壳网(58同城、链家等)抓取二手房房源信息,首先需要通过网络请求获取网页源码,然后利用BeautifulSoup解析HTML内容找到包含房源数据的部分。
以下是简单的步骤:
1. **安装所需的库**:
安装`requests`库用于发送HTTP请求,以及`beautifulsoup4`库用于处理HTML。可以在命令行运行以下命令:
```
pip install requests beautifulsoup4
```
2. **编写代码**:
```python
import requests
from bs4 import BeautifulSoup
def get_house_data(url):
# 发送GET请求
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 解析HTML内容
soup = BeautifulSoup(response.text, 'html.parser')
# 使用CSS选择器或BeautifulSoup的方法定位到房源数据
house_list = soup.select('.house-item') or soup.find_all('div', class_='house-item') # 根据实际网站结构调整
houses = []
for house in house_list:
title = house.find('h3', class_='title')['title'] if house.h3 else ''
price = house.find('span', class_='price')['data-price'] if house.span else ''
# 提取其他属性,如地址、面积等,同样根据HTML结构查找
properties = {'title': title, 'price': price} # 添加更多属性
houses.append(properties)
return houses
else:
print(f"Failed to fetch data, status code: {response.status_code}")
url = "https://example.sh.ke.com/二手房" # 替换为实际贝壳网的二手房页面URL
houses = get_house_data(url)
# 打印获取的数据
for house in houses:
print(house)
阅读全文
相关推荐



















