Xpath安装及使用

简介: Xpath安装及使用

1、xpath

1.1、xpath环境

浏览器下载xpath插件

chrome插件下载

提取码:5iex

python安装lxml库

pip install lxml -i https://pypi.douban.com/simple

1.2、xpath使用

1.etree.parse() 解析本地文件

html_tree = etree.parse(‘xxx.html’)


2.etree.HTML() 服务器响应文件

html_tree = etree.HTML(response.read().decode(‘utf-8’))


3.html_tree.xpath(xpath路径)


4.路径获取

鼠标右键查看网页源代码

快捷键 Ctrl + Shift + x 打开xpath工具

在Query框输入路径,在Result中显示定位的值


1.3、xpath基本语法

1.路径查询

//:查询所有子孙节点,不考虑层级关系

/:找直接子节点

2.谓词查询

//div[@id]

//div[@id=“maincontent”]

3.属性查询

//@class

4.模糊查询

//div[contains(@id,“he”)]

//div[start-with(@id,“he”)]

5.内容查询

//div/h1/text()

6.逻辑运算

//div[@id=“head” and @class=“s_down”]

//title | //price

1.4、应用实例:爬取站长素材图片

import urllib.request
from lxml import etree
def create_request(page):
   if (page == 1):
      url = 'https://sc.chinaz.com/tupian/meinvtupian.html'
   else:
      url = 'https://sc.chinaz.com/tupian/meinvtupian_' + str(page) + '.html'
   headers = {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
   }
   request = urllib.request.Request(url=url,headers=headers)
   return request
def get_content(request):
   response = urllib.request.urlopen(request)
   content = response.read().decode('utf-8')
   return content
def down_load(content):
   # 解析网页源码
   tree = etree.HTML(content)
   name_list = tree.xpath('//div[@id="container"]//a/img/@alt')
   src_list = tree.xpath('//div[@id="container"]//a/img/@src')
   # 下载图片到本地
   for i in range(len(name_list)):
      name = name_list[i]
       src = src_list[i]
       url = 'https:' + src
       urllib.request.urlretrieve(url=url,filename='./images/'+name+'.jpg')
if __name__ == '__main__':
   start_page = int(input("请输入起始页码:"))
   end_page = int(input("请输入结束页码:"))
   for page in range(start_page, end_page + 1):
        request = create_request(page)
        content = get_content(request)
        down_load(content)

2、jsonpath

文章推荐:https://blog.csdn.net/luxideyao/article/details/77802389

3、bs4

相关文章
|
10月前
|
JSON 分布式计算 网络协议
如何安装FreeIPA
如何安装FreeIPA
168 0
|
10月前
|
缓存 Apache
执行命令安装Apache及其扩展包时报错
执行命令安装Apache及其扩展包时报错
199 1
|
Python Windows
一、如何完全卸载Anaconda(如何下载Anaconda-Clean package)
一、如何完全卸载Anaconda(如何下载Anaconda-Clean package)
10296 0
一、如何完全卸载Anaconda(如何下载Anaconda-Clean package)
|
Ubuntu
Ubuntu20.04安装软件报错:The following packages have unmet dependencies
Ubuntu20.04安装软件报错:The following packages have unmet dependencies
859 0
Ubuntu20.04安装软件报错:The following packages have unmet dependencies
|
Ubuntu
Ubuntu设置apt代理(使用Synaptic Package Manager 新立得软件包管理器、修改 /etc/apt/apt.conf.d/proxy.conf 文件、修改 .bashrc)
Ubuntu设置apt代理(使用Synaptic Package Manager 新立得软件包管理器、修改 /etc/apt/apt.conf.d/proxy.conf 文件、修改 .bashrc)
386 0
Ubuntu设置apt代理(使用Synaptic Package Manager 新立得软件包管理器、修改 /etc/apt/apt.conf.d/proxy.conf 文件、修改 .bashrc)
|
Ubuntu 定位技术
|
开发者
xpath的详细安装方法
xpath的详细安装方法
281 0
|
Linux
packetdrill工具安装
packetdrill工具安装
225 0
packetdrill工具安装
|
分布式计算 监控 Hadoop