以下是用Python编写的代码,实现从58同城网站获取二手房信息的爬虫功能:

import requests
from lxml import etree

# 获取网站的HTML代码
url = 'https://bj.58.com/ershoufang/pn1/'
response = requests.get(url)
html = response.text

# 创建etree_html对象
etree_html = etree.HTML(html)

# 解析页面数据
house_list = etree_html.xpath('//ul[@class="house-list-wrap"]/li')
for house in house_list:
    title = house.xpath('.//h2/a/text()')[0]
    price = house.xpath('.//div[@class="price"]/p/text()')[0]
    print('房屋标题:', title)
    print('房屋价格:', price)
    print('--------------------')

这段代码首先使用requests库发送GET请求获取网站的HTML代码,然后使用lxml库的etree模块创建etree_html对象。最后,使用xpath方法解析页面数据,提取房屋标题和价格信息。您可以根据实际情况调整解析的数据内容。

代码说明:

  • requests.get(url):发送GET请求获取网站的HTML代码。
  • etree.HTML(html):创建etree_html对象,用于解析HTML代码。
  • etree_html.xpath('//ul[@class="house-list-wrap"]/li'):使用xpath方法定位页面中包含房屋信息的元素。
  • house.xpath('.//h2/a/text()')[0]:提取房屋标题文本。
  • house.xpath('.//div[@class="price"]/p/text()')[0]:提取房屋价格文本。
Python爬虫实战:获取58同城二手房信息

原文地址: https://www.cveoy.top/t/topic/f4pt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录