5.数据采集与存储2 (1)数据采集网址为链家广州租房https://gz.lianjia.com/zufang/; (2)采集该网站广州所有城区的前5页的租房信息,采集信息包括:城区、房源标题、房源面积、房源朝向、价格; (3)采集信息存
时间: 2024-04-02 21:31:33 浏览: 15
储至本地的Excel文件中,每个城区单独存储为一个Sheet,文件命名为“广州租房信息.xlsx”。以下是Python代码实现:
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
# 设置请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
# 设置要采集的城区和页数
districts = ['tianhe', 'yuexiu', 'liwan', 'haizhu', 'panyu', 'baiyun', 'huangpugz', 'nansha']
pages = 5
# 创建一个空的DataFrame
df = pd.DataFrame(columns=['城区', '房源标题', '房源面积', '房源朝向', '价格'])
# 循环遍历每个城区和页数
for district in districts:
for page in range(1, pages+1):
url = f'https://gz.lianjia.com/zufang/{district}/pg{page}/'
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
items = soup.select('.content__list--item')
# 循环遍历每个房源信息并保存到DataFrame中
for item in items:
title = item.find('p', class_='content__list--item--title').text.strip()
area = item.find('span', class_='content__list--item--size').text.strip()
direction = item.find('span', class_='content__list--item--orientation').text.strip()
price = item.find('span', class_='content__list--item-price').text.strip()
df = df.append({'城区': district, '房源标题': title, '房源面积': area, '房源朝向': direction, '价格': price}, ignore_index=True)
# 将DataFrame保存为Excel文件
with pd.ExcelWriter('广州租房信息.xlsx') as writer:
for district in districts:
temp_df = df[df['城区'] == district]
temp_df.to_excel(writer, sheet_name=district, index=False)
print('数据采集完成!')
```
这段代码使用了requests和BeautifulSoup库来请求和解析网页。首先设置了请求头,然后循环遍历每个城区和页数,将每个房源信息保存到DataFrame中。最后使用pandas库将DataFrame保存为Excel文件,并为每个城区单独创建一个Sheet。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![csv](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)