笨鸟编程-零基础入门Pyhton教程

 找回密码
 立即注册

选择器

发布者: 笨鸟自学网



实例

HTML响应的选择器示例

这里有一些 Selector 举例说明几个概念。在所有情况下,我们假设 Selector 用一个 HtmlResponse 这样的对象:

sel = Selector(html_response)
  1. 选择全部 <h1> 来自HTML响应正文的元素,返回 Selector 对象(即 SelectorList 对象):

    sel.xpath("//h1")
    
  2. 提取所有文本 <h1> 元素,返回字符串列表:

    sel.xpath("//h1").getall()         # this includes the h1 tag
    sel.xpath("//h1/text()").getall()  # this excludes the h1 tag
    
  3. 全部迭代 <p> 标记并打印其类属性:

    for node in sel.xpath("//p"):
        print(node.attrib['class'])
    

XML响应的选择器示例

下面是一些例子来说明 Selector 对象用 XmlResponse 对象:

sel = Selector(xml_response)
  1. 选择全部 <product> 来自XML响应主体的元素,返回 Selector 对象(即 SelectorList 对象):

    sel.xpath("//product")
    
  2. 从A中提取所有价格 Google Base XML feed 需要注册命名空间::

    sel.register_namespace("g", "http://base.google.com/ns/1.0")
    sel.xpath("//g:price").getall()
上一篇:蜘蛛下一篇:项目

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2024-9-8 11:51 , Processed in 0.026976 second(s), 17 queries .

© 2001-2020

返回顶部