zoukankan      html  css  js  c++  java
  • 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, "id+")]')        # 所有a标签 属性id的值 符合正则表达式"id+"的规则
    
    xpath('//a[re:test(@id, "id+")]/text()').extract()        # 所有a标签,取text的值
    xpath('//a[re:test(@id, "id+")]/@href').extract()        # 所有a标签,取href的属性值
    
    xpath('/html/body/ul/li/a/@href').extract()        # 取所有的值
    xpath('//body/ul/li/a/@href').extract_first()    # 取第一个值
  • 相关阅读:
    LINUX查看进程开始时间、结束时间、运行时间
    excel字符处理函数
    oracle RMAN参数配置详解
    Linux添加双IP
    免费软电话 — XLite 的安装及配置向导
    Asterisk实现寻呼对讲广播的Page()命令详解
    自动化工具的重要性
    负载均衡之应用请求路由模块的使用(ARR)(七)[使用ARR来实现主机名共享]
    负载均衡之应用请求路由模块的使用(ARR)(二)[安装]
    需求管理随笔
  • 原文地址:https://www.cnblogs.com/wt7018/p/11749778.html
Copyright © 2011-2022 走看看