爬取58同城二手房中的房源信息
from lxml import etree
import requests
# 爬取页面源码数据
url = 'https://sz.58.com/ershoufang/'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 '
'Safari/537.36'
}
page_text = requests.get(url=url,headers=headers).text
# 解析数据
tree = etree.HTML(page_text)
li_list = tree.xpath = ('//section[@class="list"]/div')
fp = open('58.txt','w',encoding='utf-8')
for li in li_list:
# 局部解析
title = li.xpath('./div[2]/div[1]/div[1]/h3/text()')[0]
print(title)
fp.write(title + '\n')