Python爬虫-利用xpath解析爬取58二手房详细信息

前言

简单的Python练习,对页面中的某些部分的文字进行爬取

介绍

在这里插入图片描述

xpath解析: 最常用且最便捷高效的一种解析方式。通用型。
    -xpath解析原理:
        - 1. 实例化一个etree的对象,且需要将被解析的页面源码数据加载到该对象中。
        - 1. 调用etree对象中的xpath方法结合着xpath表达式实现标签的定位和内容的捕获。
    环境的安装:
        - pip install lxml
    -如何实例化一个entree对象:from lxml import etree
        - 1. 将本地的html文档中的源码数据加载到etree对象中:
            etree.parse(filePath)
        - 2. 可以将从互联网上获取的源码数据加载到该对象中
            etree.HTML('page_text'-xpath('xpath表达式'-xpath表达式:
        - /:表示的是从一个根节点开始定位,表示一个层级。
        - //:表示的是多个层级,可以从任意位置开始定位。
        - 属性定位://div[@class='song'] tag[@attrName='attrValue']
        - 索引定位://div[@calss+'song']/p[3] 索引是从1开始的。
        - 取文本:
            - /text() 获取的是标签中的直系文本内容
            - //text() 获取的标签中的非直系的文本内容(所有的文本内容)
        - 取属性:
            /@attrName ==>img/src

代码

import requests
from lxml import html
etree = html.etree
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 Edg/92.0.902.55'
}
url ='https://shangshui.58.com/ershoufang/?'
page_text = requests.get(url=url,headers=headers).text
#print(page_text)
tree = etree.HTML(page_text)
li_list = tree.xpath('//section[@class="list"][1]/div')
# print(li_list)
fp = open('58.txt','w',encoding='utf-8')
for li in li_list:
    title = li.xpath('./a//div[@class="property-content-detail"]//text()')
    price= li.xpath('./a//div[@class="property-price"]//text()')
    # print(price)
    titles=''
    prices=''
    for i in range(len(title)):

        if title[i]!=', ' and title[i]!=' ':
            titles += title[i].strip()
            titles += " "
        i+=1
    for j in range(len(price)):
        if price[j]!=', ' and price[j]!=' ':
            prices +=price[j].strip()
            prices +=" "
        j+=1
    titles_and_prices= titles+prices+'。\n'
    fp.write(titles_and_prices)
    print(titles_and_prices)

运行结果截图

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Tom197/article/details/119322307