zoukankan      html  css  js  c++  java
  • python爬虫框架scrapy初试(二)

    将该导航网站搜索出结果的页面http://www.dmoz.org/Computers/Programming/Languages/Python/Books/里面标题,及标题的超链接和描述爬下来。

    使用scrapy抓取一个网站一共需要四个步骤。

    ---创建一个scrapy项目

    ---定义item容器

    ---编写爬虫

    ---储存内容

    1.新建一个项目

    scrapy startproject demoscrapy

    2.定义item容器(定义要爬取的内容)

    3.编写爬虫(这里以官网的教程为例子)

    import scrapyclass Dmos_spider(scrapy.Spider):
        name = 'dmoz'        #爬虫的名字
        allowed_domains = ['dmoz.org']        #爬虫允许域名范围
        start_urls = [
            'http://www.dmoz.org/Computers/Programming/Languages/Python/Books/',        #爬取的页面
            'http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/'
            ]
    

    4.储存内容

    import scrapy
    from demoscrapy.items import DemoscrapyItem
    class Dmos_spider(scrapy.Spider):
        name = 'dmoz'
        allowed_domains = ['dmoz.org']
        start_urls = [
            'http://www.dmoz.org/Computers/Programming/Languages/Python/Books/',
            'http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/'
            ]
        def parse(self,response):    #处理爬去结果
            sel = scrapy.selector.Selector(response)  
            items = []
            sites = sel.xpath('//*[@id="site-list-content"]/div/div[3]')    #通过xpath处理页面节点
            for site in sites:
                item = DemoscrapyItem()
    
                item['title'] = site.xpath('a/div/text()').extract()
                item['link'] = site.xpath('a/@href').extract()
                item['desc'] = site.xpath('div/text()').extract()
                items.append(item)
            return  items

    scrapy crawl dmoz -o items.json -t json 

    -o 输出文件 -t 以json格式储存

    注*在存储的时候,要通过xpath抓取想要的数据。

    google浏览器有xpath插件可以安装下。

    更详细的xpath教程

    http://www.w3school.com.cn/xpath/index.asp

  • 相关阅读:
    python中的if...else...、while、for
    linux的/etc/passwd、/etc/shadow、/etc/group和/etc/gshadow
    [国家集训队]middle
    [SCOI2007]修车
    基本图论-连通分量(强/弱联通 割点/边 边/点双)
    [NOI2008]奥运物流
    [NOI2008]假面舞会
    [NOI2008]设计路线
    [SCOI2009]windy数
    [SCOI2013]多项式的运算
  • 原文地址:https://www.cnblogs.com/cui0x01/p/6211982.html
Copyright © 2011-2022 走看看