Scrapy解析器xpath

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

猜你喜欢

转载自www.cnblogs.com/wt7018/p/11749778.html
今日推荐