python爬虫Xpath和CSS选择器的使用例子

最近学习用 Scrapy 框架写爬虫,简单来说爬虫就是从网上抓取网页,解析网页,然后进行数据的存储与分析,将从网页的解析到数据的转换存储。将学习过程中用到的解析技术,Scrapy 的各个模块使用与进阶到分布式爬虫学到的知识点、遇到的问题以及解决方法记录于此,以作总结与备忘。

# -*- coding: GBK -*-
import scrapy

from scrapy.selector import Selector

"""
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
  <title lang="chin">Harry Potter</title>
  <price>29.99</price>
</book>
<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>
</bookstore>
"""
def test():
    with open("xpathTest1.txt","r") as fp:
        body = fp.read()
        aitems=Selector(text=body).xpath("//book").extract()
        for a in aitems:
            print a
        print "============================="
        #结果
        #<title lang="chin">Harry Potter</title>
        #<title lang="eng">Learning XML</title>
        bitems = Selector(text=body).xpath("//title[@lang]").extract()
        for b in bitems:
            print b
        print "============================="
        #<title lang="eng">Learning XML</title>
        bitems = Selector(text=body).xpath("//title[@lang='eng']").extract()
        for b in bitems:
            print b
        print "============================="
        #<Selector xpath='//title[@lang]' data=u'<title lang="eng">Learning XML</title>'>
        print Selector(text=body).xpath("//title[@lang]")[1]
        print Selector(text=body).xpath("//bookstore/book")[1]
        print "============================="
        #<title lang="eng">Learning XML</title>
        bitems = Selector(text=body).xpath("//bookstore/book").extract()
        for b in bitems:
            print b
        print "============================="
        """
        <book>
          <title lang="eng">Learning XML</title>
          <price>39.95</price>
        </book>
        """
        bitems = Selector(text=body).xpath("//bookstore/book[price>35.00]").extract()
        for b in bitems:
            print b
        print "============================="
        # []
        print Selector(text=body).xpath("/title")
#test()
def test2():
    with open("xpathTest1.txt","r") as fp:
        body = fp.read()
        """
        <book>
           <title lang="chin">Harry Potter</title>
           <price>29.99</price>
        </book>
        <book>
          <title lang="eng">Learning XML</title>
          <price>39.95</price>
       </book>
        """
        aitems=Selector(text=body).css("book").extract()
        for a in aitems:
            print a
        print "============================="
        # 结果
        # <title lang="chin">Harry Potter</title>
        # <title lang="eng">Learning XML</title>
        aitems = Selector(text=body).css("title").extract()
        for a in aitems:
            print a
        aitems = Selector(text=body).css("book price").extract()
        for a in aitems:
            print a
        print "============================="
        aitems = Selector(text=body).css("[lang]").extract()
        for a in aitems:
            print a
        print "============================="
        aitems = Selector(text=body).css("[lang='eng']").extract()
        for a in aitems:
            print a
        print "============================="
test2()

本篇主要讲解 xpath 、css 解析网页的语法以及在 Scrapy 中的使用方式

一. xpath 简介与语法概要
xpath 是 w3c 的一种标准。简单来说就是可以让我们以路径的形式访问 html 网页中的各个元素。其中最主要的两个 为 // 与 /。前者代表 路径下的所有元素, 后者代表路径下的子元素。具体语法如下:
选取节点
XPath 使用路径表达式在 XML 文档中选取节点。节点是通过沿着路径或者 step 来选取的。
下面列出了最有用的路径表达式:

表达式 描述
nodename 选取此节点的所有子节点。
/ 从根节点选取。
// 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
. 选取当前节点。
… 选取当前节点的父节点。
@ 选取属性。
实例
在下面的表格中,我们已列出了一些路径表达式以及表达式的结果:
路径表达式 结果
bookstore 选取 bookstore 元素的所有子节点。
/bookstore 选取根元素 bookstore。注释:假如路径起始于正斜杠( / ),则此路径始终代表到某元素的绝对路径!
bookstore/book 选取属于 bookstore 的子元素的所有 book 元素。
//book 选取所有 book 子元素,而不管它们在文档中的位置。
bookstore//book 选择属于 bookstore 元素的后代的所有 book 元素,而不管它们位于 bookstore 之下的什么位置。
//@lang 选取名为 lang 的所有属性。
谓语(Predicates)
谓语用来查找某个特定的节点或者包含某个指定的值的节点。
谓语被嵌在方括号中。
实例
在下面的表格中,我们列出了带有谓语的一些路径表达式,以及表达式的结果:

路径表达式 结果
/bookstore/book[1] 选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()] 选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1] 选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position()❤️] 选取最前面的两个属于 bookstore 元素的子元素的 book 元素。
//title[@lang] 选取所有拥有名为 lang 的属性的 title 元素。
//title[@lang=‘eng’] 选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。
/bookstore/book[price>35.00] 选取 bookstore 元素的所有 book 元素,且其中的 price 元素的值须大于 35.00。
/bookstore/book[price>35.00]/title 选取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值须大于 35.00。
选取若干路径
通过在路径表达式中使用“|”运算符,您可以选取若干个路径。
实例
在下面的表格中,我们列出了一些路径表达式,以及这些表达式的结果:
路径表达式 结果
//book/title | //book/price 选取 book 元素的所有 title 和 price 元素。
//title | //price 选取文档中的所有 title 和 price 元素。
/bookstore/book/title | //price 选取属于 bookstore 元素的 book 元素的所有 title 元素,以及文档中所有的 price 元素。
二. css 语法概要
熟悉前端的同学对 css 选择器一定不会陌生,比如 jquery 中通过各种 css 选择器语法进行 DOM 操作等。这里对其语法进行简要的总结,便于复习。
CSS3 选择器
在 CSS 中,选择器是一种模式,用于选择需要添加样式的元素。
“CSS” 列指示该属性是在哪个 CSS 版本中定义的。(CSS1、CSS2 还是 CSS3。)
选择器 例子 例子描述
.class .intro 选择 class=“intro” 的所有元素。
#id #firstname 选择 id=“firstname” 的所有元素。

    • 选择所有元素。
      element p 选择所有

      元素。
      element,element div,p 选择所有

      元素和所有

      元素。
      element element div p 选择

      元素内部的所有

      元素。
      element>element div>p 选择父元素为

      元素的所有

      元素。
      element+element div+p 选择紧接在

      元素之后的所有

      元素。
      [attribute] [target] 选择带有 target 属性所有元素。
      [attribute=value] [target=_blank] 选择 target="_blank" 的所有元素。
      [attribute~=value] [title~=flower] 选择 title 属性包含单词 “flower” 的所有元素。
      [attribute|=value] [lang|=en] 选择 lang 属性值以 “en” 开头的所有元素。
      :link a:link 选择所有未被访问的链接。
      :visited a:visited 选择所有已被访问的链接。
      :active a:active 选择活动链接。
      :hover a:hover 选择鼠标指针位于其上的链接。
      :focus input:focus 选择获得焦点的 input 元素。
      :first-letter p:first-letter 选择每个

      元素的首字母。
      :first-line p:first-line 选择每个

      元素的首行。
      :first-child p:first-child 选择属于父元素的第一个子元素的每个

      元素。
      :before p:before 在每个

      元素的内容之前插入内容。
      :after p:after 在每个

      元素的内容之后插入内容。
      :lang(language) p:lang(it) 选择带有以 “it” 开头的 lang 属性值的每个

      元素。
      element1~element2 p~ul 选择前面有

      元素的每个

      • 元素。
        [attribute^=value] a[src^=“https”] 选择其 src 属性值以 “https” 开头的每个 元素。
        [attribute = v a l u e ] a [ s r c =value] a[src =value]a[src=".pdf"] 选择其 src 属性以 “.pdf” 结尾的所有 元素。
        [attribute*=value] a[src*=“abc”] 选择其 src 属性中包含 “abc” 子串的每个 元素。
        :first-of-type p:first-of-type 选择属于其父元素的首个

        元素的每个

        元素。
        :last-of-type p:last-of-type 选择属于其父元素的最后

        元素的每个

        元素。
        :only-of-type p:only-of-type 选择属于其父元素唯一的

        元素的每个

        元素。
        :only-child p:only-child 选择属于其父元素的唯一子元素的每个

        元素。
        :nth-child(n) p:nth-child(2) 选择属于其父元素的第二个子元素的每个

        元素。
        :nth-last-child(n) p:nth-last-child(2) 同上,从最后一个子元素开始计数。
        :nth-of-type(n) p:nth-of-type(2) 选择属于其父元素第二个

        元素的每个

        元素。
        :nth-last-of-type(n) p:nth-last-of-type(2) 同上,但是从最后一个子元素开始计数。
        :last-child p:last-child 选择属于其父元素最后一个子元素每个

        元素。
        :root :root 选择文档的根元素。
        :empty p:empty 选择没有子元素的每个

        元素(包括文本节点)。
        :target #news:target 选择当前活动的 #news 元素。
        :enabled input:enabled 选择每个启用的 元素。
        :disabled input:disabled 选择每个禁用的 元素
        :checked input:checked 选择每个被选中的 元素。
        :not(selector) :not§ 选择非

        元素的每个元素。
        ::selection ::selection 选择被用户选取的元素部分。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值