import requests
from bs4 import BeautifulSoup
import re
from lxml import etree
import time
# 需求:爬取58二手房的房源信息
if __name__ == "__main__":
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36'
}
# 爬取到页面源码数据
url = 'https://bz.58.com/ershoufang/?utm_source=market&spm=u-2d2yxv86y3v43nkddh1.BDPCPZ_BT&PGTID=0d100000-003b-0e56-85b3-c5c32ec9116c&ClickID=4'
page_text = requests.get(url=url, headers=headers).text
# 数据解析
tree = etree.HTML(page_text)
# 存储li标签对象
li_list = tree.xpath('//ul[@class="house-list-wrap"]/li')
fp = open('58.txt', 'w', encoding='utf-8')
for li in li_list:
# 从当前li标签中解析出a标签
title = li.xpath('./div[2]/h2/a/text()')[0] # ./标识的就是li.xpath里的li(整个页面源码的局部内容),也就是表示从当前的li开始为根节点进行搜索
print(title)
# 数据持久化存储
fp.write(title+'\n')
爬取58二手房的放原标题
最新推荐文章于 2024-03-17 19:35:10 发布