一、使用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() # 取第一个值

最新文章

  1. linux学习笔记2-命令总结4
  2. Project Euler 107:Minimal network 最小网络
  3. 【BZOJ】【1029】【JSOI2007】建筑抢修
  4. Java字符串的10大热点问题,你都懂吗?
  5. android怎样写一个循环文字滚动的TextView
  6. Unity2D开发小细节
  7. C#使用LitJson解析JSON(转)
  8. Firebase 相关
  9. WinForm中控件位置不随窗体大小的变化而改变
  10. 怎么调试nodejs restful API 以及API的Authorization
  11. es6之let和const命令的一些笔记
  12. 操作系统内核Hack:(四)内核雏形
  13. asp.net webapi中helppage
  14. java:tomcat(负载均衡)nginx的应用配置
  15. 安全之路 —— 利用APC队列实现跨进程注入
  16. 2018蓝桥杯 省赛B题(明码)
  17. Specified version of key is not available (44)
  18. git起步
  19. centos7.2 源码编译安装php7.2.4 apache2.4.37 https证书安装
  20. MD5加密获得文件的MD5码

热门文章

  1. 21个项目玩转深度学习:基于TensorFlow的实践详解01—MNIST机器学习入门
  2. P1063 高兴的津津
  3. Linux内核接口特定的类型
  4. 轮播图模块(vue)
  5. easyUI demo2
  6. xcode无线调试
  7. 使用windows api函数捕获SAP session的左下角消息句柄
  8. docker安装启动、配置MySql
  9. appium启动app(android)
  10. 配置一个yum私有仓库