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()    # 取第一個值

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM