用python爬虫获取房原码
时间: 2024-05-09 15:12:08 浏览: 6
使用Python进行爬虫获取房源码,一般需要以下步骤:
1. 选择爬取的网站,并分析该网站的HTML结构及数据获取方式。
2. 使用Python中的requests库向目标网站发送HTTP请求,获取网页源代码。
3. 使用正则表达式或者BeautifulSoup等库,从网页源代码中提取所需的数据。
4. 保存数据到本地或者数据库中。
下面是一个简单的示例代码,以爬取链家网站上北京市二手房信息为例:
```
import requests
from bs4 import BeautifulSoup
url = 'https://bj.lianjia.com/ershoufang/'
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.36'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
house_list = soup.find('ul', class_='sellListContent').find_all('li')
for house in house_list:
title = house.find('div', class_='title').text.strip()
link = house.find('a')['href']
price = house.find('div', class_='totalPrice').text.strip()
print(title, link, price)
```