Scrapy解析器xpath
2024-09-01 07:31:51
一、使用xpath
不在scrapy框架中通过response
from scrapy.http import HtmlResponse
HtmlResponse->TextResponse->self.selector.xpath(query, **kwargs)->selector(self)->from scrapy.selector import Selector
1、方法一 HtmlResponse(推荐)
from scrapy.http import HtmlResponse html = """
html网页
"""
# 注意这个url是任意的,但是必须填写
response = HtmlResponse(url='http://example.com', body=html, encoding='utf-8')
ret = response.xpath('//ul/li[@class="item-0"]/a[@id="i2"]/text()').extract_first()
print(ret)
2、方法二 Selector
from scrapy.http import HtmlResponse
from scrapy.selector import Selector html = """
html网页
""" response = HtmlResponse(url='http://example.com', body=html, encoding='utf-8')
selector = Selector(response)
ret = selector.xpath('//ul/li[@class="item-0"]/a[@id="i2"]/text()').extract_first()
print(ret)
二、选择器
xpath('//a') # 所有a标签(子孙后代)
xpath('//a[2]') # 所有a标签,按索引找第二个 xpath('//a[@id]') # 所有a标签,并且含有id属性
xpath('//a[@id="i1"]') # 所有a标签,并且属性id='i1'
xpath('//a[@href="link.html"][@id="i1"]') # 所有a标签,属性href="link.html" 而且 id="i1" xpath('//a[contains(@href, "link")]') # 所有a标签,属性href的值包含"link"
xpath('//a[starts-with(@href, "link")]') # 所有a标签,属性href的值以"link"开头
xpath('//a[re:test(@id, "i\d+")]') # 所有a标签 属性id的值 符合正则表达式"i\d+"的规则 xpath('//a[re:test(@id, "i\d+")]/text()').extract() # 所有a标签,取text的值
xpath('//a[re:test(@id, "i\d+")]/@href').extract() # 所有a标签,取href的属性值 xpath('/html/body/ul/li/a/@href').extract() # 取所有的值
xpath('//body/ul/li/a/@href').extract_first() # 取第一个值
最新文章
- linux学习笔记2-命令总结4
- Project Euler 107:Minimal network 最小网络
- 【BZOJ】【1029】【JSOI2007】建筑抢修
- Java字符串的10大热点问题,你都懂吗?
- android怎样写一个循环文字滚动的TextView
- Unity2D开发小细节
- C#使用LitJson解析JSON(转)
- Firebase 相关
- WinForm中控件位置不随窗体大小的变化而改变
- 怎么调试nodejs restful API 以及API的Authorization
- es6之let和const命令的一些笔记
- 操作系统内核Hack:(四)内核雏形
- asp.net webapi中helppage
- java:tomcat(负载均衡)nginx的应用配置
- 安全之路 —— 利用APC队列实现跨进程注入
- 2018蓝桥杯 省赛B题(明码)
- Specified version of key is not available (44)
- git起步
- centos7.2 源码编译安装php7.2.4 apache2.4.37 https证书安装
- MD5加密获得文件的MD5码