xpath 解析 及案例

xpath解析

  • 编码流程:
    • 1.实例化一个etree对象,且将页面源码加载到该对象中
    • 2.使用xpath函数,且在函数中必须作用一个xpath表达式进行标签的定位
    • 3.使用xpath进行属性和文本的提取
  • xpath表达式:
    • / and //
    • 索引和属性定位://a[1] //a[@tagName]
    • /text() //text()
    • //a/@attrName
    • xpath函数返回的一定是一个列表
- 环境安装:
    - pip install lxml
- 解析原理:
    - 实例化一个etree的对象,且将页面源码数据加载到该对象中
    - 调用etree对象中的xpath方法实现标签定位和数据的提取
    - 在xpath函数中必须作用xpath表达式
  • 将 response.text 放到 etree.HTML( 中 ) 返回 tree 进行.xpath操作
  • 取文本信息
    • /text() 单层 //text() 多层
  • 取属性
    • /@alt
    • /@src
  • 可使用:
  • tree.xpath('//div[@class="hot"]/div[@class="bottom"]/ul/li/a/text() | //div[@class="all"]/div[@class="bottom"]/ul/div[2]/li/a/text()')

  • 解析某二手房信息
import requests
from lxml import etree
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
}

url = 'https://bj.*****.com/shahe/ershoufang/pn1/'
page_text = requests.get(url=url,headers=headers).text
#数据解析(名称,单价/总价,详情)
tree = etree.HTML(page_text)
#li_list列表元素都是li标签对象
li_list = tree.xpath('//ul[@class="house-list-wrap"]/li')
fp = open('./二手房.txt','w',encoding='utf-8')
for li in li_list:
    title = li.xpath('./div[2]/h2/a/text()')[0]
    detail = li.xpath('./div[2]/p//text()')
    detail = ''.join(detail)
    detail = detail.strip()
    price = li.xpath('./div[3]/p//text()')
    price = ''.join(price)
    price = price.strip()
    fp.write(title+':'+price+':'+detail+'\n')

fp.close()
print('over!!!')  

猜你喜欢

转载自www.cnblogs.com/zhang-zi-yi/p/10749351.html