首页 技术 正文
技术 2022年11月21日
0 收藏 911 点赞 3,549 浏览 1220 个字

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!!!')
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,000
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,512
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,358
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,141
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,771
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,849