美文网首页
8. xpath - 58房源信息爬取

8. xpath - 58房源信息爬取

作者: 薛东弗斯 | 来源:发表于2024-02-26 00:04 被阅读0次
image.png
image.png
image.png
image.png
# 需求:爬取58二手房中房源信息
import requests
from lxml import etree
if __name__=="__main__":
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/96.0.4664.45 Safari/537.36'
    }
    # 爬取到页面源码数据
    url = 'https://bj.58.com/ershoufang/'
    page_text = requests.get(url=url,headers=headers).text

    # 数据解析
    tree = etree.HTML(page_text)
    # 存储的就是li标签对象
    li_list = tree.xpath('//url[@class="house-list-wrap"]/li')
    fp = open('58.txt','w',encoding='utf-8')
    for li in li_list:
        # 局部解析
        title = li.xpath('./div[2]/h2/a/text()')[0]
        print(title)
        fp.write(title+'\n')

相关文章

网友评论

      本文标题:8. xpath - 58房源信息爬取

      本文链接:https://www.haomeiwen.com/subject/uxuoadtx.html