将代码改为爬取一部分房源信息
时间: 2023-09-17 10:08:50 浏览: 38
好的,这里是将代码修改为爬取一部分房源信息的方式:
```python
import requests
from bs4 import BeautifulSoup
url = "https://bj.5i5j.com/zufang/n{}"
# 修改这里的页码范围
for i in range(1, 6):
page_url = url.format(i)
response = requests.get(page_url)
soup = BeautifulSoup(response.text, "html.parser")
house_list = soup.find_all("div", class_="listCon")
# 修改这里的房源数量
for house in house_list[:5]:
title = house.find("p", class_="title").text.strip()
area = house.find("p", class_="area").text.strip()
price = house.find("p", class_="price").text.strip()
print(title, area, price)
```
这里我们将页码范围修改为1到5,只爬取了每页的前5个房源信息。你可以根据自己的需求修改这两个参数。
相关问题
为我写一段爬虫代码,用于爬取网站信息
好的,很高兴为您提供帮助。以下是一段简单的Python爬虫代码,可用于爬取网站信息:
```
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com/" # 请替换为您要爬取的网站
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
# 在此处添加您需要的页面信息提取代码,例如:
title = soup.title.string
print("网站标题为:", title)
```
请注意,在实际使用中,您需要根据具体情况对代码进行修改。另外,爬取网站信息要求遵守相关法律法规,切勿进行任何侵犯他人权益的操作。
用python爬取链家网二手房信息武汉藏龙岛部分
好的,以下是使用Python爬取链家网二手房信息武汉藏龙岛部分的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 设置请求参数
params = {
'page': 1, # 页数
'district_id': '103102785927', # 行政区id,武汉市-江夏区-藏龙岛
'sort': 'price_desc' # 排序方式:按价格降序
}
# 发送请求
url = 'https://wh.lianjia.com/ershoufang/'
res = requests.get(url, headers=headers, params=params)
# 解析数据
soup = BeautifulSoup(res.text, 'html.parser')
house_items = soup.find_all('div', class_='info clear')
for item in house_items:
# 获取房源信息
title = item.find('div', class_='title').a.text.strip() # 标题
address = item.find('div', class_='address').div.text.strip() # 地址
price = item.find('div', class_='priceInfo').div.text.strip() # 价格
print('标题:{}\n地址:{}\n价格:{}\n'.format(title, address, price))
```
以上代码实现了爬取武汉藏龙岛部分的链家网二手房信息,并按价格降序排列。可以根据需要修改参数来爬取其他区域的数据。需要注意的是,爬取网站时需要设置请求头,否则会被网站封禁。
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)