用python写一段爬取58同城租房网站的租房信息的代码
时间: 2024-06-10 21:06:48 浏览: 20
以下是爬取58同城租房网站租房信息的Python代码示例:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://sz.58.com/chuzu/'
def get_html(url):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
response.encoding = response.apparent_encoding
return response.text
except:
return ""
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
house_list = soup.find_all('div', class_='des')
for house in house_list:
title = house.find('h2').get_text()
price = house.find('b').get_text()
area = house.find_all('p')[1].get_text().strip()
print(title, price, area)
def main():
for i in range(1, 3):
html = get_html(url + 'pn' + str(i))
parse_html(html)
if __name__ == '__main__':
main()
```
这段代码可以爬取58同城深圳租房网站的前两页租房信息,包括房源标题、价格和面积。您可以根据需要修改url和页数等参数。
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)