Scrapy学习系列(一):网页元素查询CSS Selector和XPath Selector

这篇文章主要介绍创建一个简单的spider,顺便介绍一下对网页元素的选取方式(css selector, xpath selector)。

第一步:创建spider工程

打开命令行运行以下命令:

scrapy startproject homelink_selling_index

创建出的工程结构如下:

│  scrapy.cfg

│

└─lianjia_shub

    │  items.py

    │  pipelines.py

    │  settings.py

    │  __init__.py

    │

    └─spiders

            __init__.py

第二步:定义spider(homelink_selling_index

需要抓取的页面元素如下图:

导入命名空间:

import scrapy

定义spider:

class homelink_selling_index_spider(scrapy.Spider):

    # 定义spider的名字,在调用spider进行crawling的时候会用到:
    #   scrapy crawl <spider.name>
    name = "homelink_selling_index"
    # 如果没有特别指定其他的url,spider会以start_urls中的链接为入口开始爬取
    start_urls = ["http://bj.lianjia.com/ershoufang/pg1tt2/"]

    # parse是scrapy.Spider处理http response的默认入口
    # parse会对start_urls里的所有链接挨个进行处理
    def parse(self, response):
        # 获取当前页面的房屋列表
        #house_lis = response.css('.house-lst .info-panel')
        house_lis = response.xpath('//ul[@class="house-lst"]/li/div[@class="info-panel"]')
        # 把结果输出到文件(在命令行中房屋标题会因为编码原因显示为乱码)
        with open("homelink.log", "wb") as f:
            ## 使用css selector进行操作
            #average_price = response.css('.secondcon.fl li:nth-child(1)').css('.botline a::text').extract_first()
            #f.write("Average Price: " + str(average_price) + "
")
            #yesterday_count = response.css('.secondcon.fl li:last-child').css('.botline strong::text').extract_first()
            #f.write("Yesterday Count: " + str(yesterday_count) + "
")
            #for house_li in house_lis:
            #    link = house_li.css('a::attr("href")').extract_first()             # 获取房屋的链接地址
            #    title = house_li.css('a::text').extract_first()                    # 获取房屋的标题
            #    price = house_li.css('.price .num::text').extract_first()          # 获取房屋的价格

            # 使用xpath selector进行操作
            average_price = response.xpath('//div[@class="secondcon fl"]//li[1]/span[@class="botline"]//a/text()').extract_first()
            f.write("Average Price: " + str(average_price) + "
")
            yesterday_count = response.xpath('//div[@class="secondcon fl"]//li[last()]//span[@class="botline"]/strong/text()').extract_first()
            f.write("Yesterday Count: " + str(yesterday_count) + "
")
            for house_li in house_lis:
                link = house_li.xpath('.//a/@href').extract_first()                 # 注意这里xpath的语法,前面要加上".",否则会从文档根节点而不是当前节点为起点开始查询
                title = house_li.xpath('.//a/text()').extract_first()
                price = house_li.xpath('.//div[@class="price"]/span[@class="num"]/text()').extract_first()
                f.write("Title: {0}	Price:{1}
	Link: {2}
".format(title.encode('utf-8'), price, link))

第三步:查看结果

Average Price: 44341
Yesterday Count: 33216
Title: 万科假日风景全明格局 南北精装三居 满五唯一	Price:660
	Link: http://bj.lianjia.com/ershoufang/xxx.html
Title: 南北通透精装三居 免税带车位 前后对花园 有钥匙	Price:910
	Link: http://bj.lianjia.com/ershoufang/xxx.html
Title: 西直门 时代之光名苑 西南四居 满五唯一 诚心出售	Price:1200
	Link: http://bj.lianjia.com/ershoufang/xxx.html
......

结语:

通过上面的三步,我们可以对网页元素进行简单的爬取操作了。但是这里还没有真正利用好Scrapy提供给我们的很多方便、强大的功能,比如: ItemLoader, Pipeline等。这些操作会在后续的文章中继续介绍。

原文地址:https://www.cnblogs.com/silverbullet11/p/scrapy_series_1.html