博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
scrapy的selectors
阅读量:7102 次
发布时间:2019-06-28

本文共 1189 字,大约阅读时间需要 3 分钟。

from scrapy import Selector

>>> doc = """

... <div>

...     <ul>

...         <li class="item-0"><a href="link1.html">first item</a></li>

...         <li class="item-1"><a href="link2.html">second item</a></li>

...         <li class="item-inactive"><a href="link3.html">third item</a></li>

...         <li class="item-1"><a href="link4.html">fourth item</a></li>

...         <li class="item-0"><a href="link5.html">fifth item</a></li>

...     </ul>

... </div>

... """

>>> sel = Selector(text=doc, type="html")

>>> sel.xpath('//li//@href').extract()

[u'link1.html', u'link2.html', u'link3.html', u'link4.html', u'link5.html']

在xpath中使用正则表达式

>>> sel.xpath('//li[re:test(@class, "item-\d$")]//@href').extract()

[u'link1.html', u'link2.html', u'link4.html', u'link5.html']

在xpath中使用变量,用$标识,下面路径表示提取包含5个<a>标签的div标签的属性id的值

response.xpath('//div[count(a)=$cnt]/@id',cnt=5).extract_first()

response.xpath('//div[@id=$val]/a/text()', val='images').extract_first()

u'Name: My image 1 '

 

response.xpath('//base/@href').extract()

[u'http://example.com/']

response.css('base::attr(href)').extract()

[u'http://example.com/']

response.xpath('//a[contains(@href,"img")]/@href').extract()

response.css(

转载于:https://www.cnblogs.com/Ting-light/p/9543425.html

你可能感兴趣的文章
Linux系统新手学习的11点建议
查看>>
Github上传代码菜鸟超详细教程【转】
查看>>
SVN上的项目如何迁移到Git
查看>>
多级<select>选择的实现(利用selectedIndex属性)
查看>>
Apache Rewrite
查看>>
转贴: QUARTUS 实现远程控制的简单方法
查看>>
开源还是商用?十大云运维监控工具横评
查看>>
python3 科学计算2
查看>>
Mysql启动失败Can’t connect to local MySQL server throu
查看>>
大学四年的学习经历
查看>>
viewController
查看>>
Filebeat入门
查看>>
Java之字符串和字符串缓冲区
查看>>
tomcat、oracle、centos时区异常处理
查看>>
Raspberry Pi双网卡bonding
查看>>
HDU1022
查看>>
Nginx - 文章 - 伯乐在线 大量 Nginx资料
查看>>
Genymotion初体验
查看>>
JBoss 系列二十一:JBossCache 核心API
查看>>
Apache下htaccess文件不起作用/rewrite 没有效果
查看>>