欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python的Scrapy爬蟲框架簡單學習筆記

 更新時間:2016年01月20日 15:44:22   作者:明天以后  
這篇文章主要介紹了Python的Scrapy爬蟲框架簡單學習筆記,從基本的創(chuàng)建項目到CrawlSpider的使用等都有涉及,需要的朋友可以參考下

 一、簡單配置,獲取單個網(wǎng)頁上的內(nèi)容。
(1)創(chuàng)建scrapy項目

scrapy startproject getblog

(2)編輯 items.py

# -*- coding: utf-8 -*-
 
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
 
from scrapy.item import Item, Field
 
class BlogItem(Item):
  title = Field()
  desc = Field()

    (3)在 spiders 文件夾下,創(chuàng)建 blog_spider.py

需要熟悉下xpath選擇,感覺跟JQuery選擇器差不多,但是不如JQuery選擇器用著舒服( w3school教程: http://www.w3school.com.cn/xpath/  )。

# coding=utf-8
 
from scrapy.spider import Spider
from getblog.items import BlogItem
from scrapy.selector import Selector
 
 
class BlogSpider(Spider):
  # 標識名稱
  name = 'blog'
  # 起始地址
  start_urls = ['http://www.cnblogs.com/']
 
  def parse(self, response):
    sel = Selector(response) # Xptah 選擇器
    # 選擇所有含有class屬性,值為‘post_item'的div 標簽內(nèi)容
    # 下面的 第2個div 的 所有內(nèi)容
    sites = sel.xpath('//div[@class="post_item"]/div[2]')
    items = []
    for site in sites:
      item = BlogItem()
      # 選取h3標簽下,a標簽下,的文字內(nèi)容 ‘text()'
      item['title'] = site.xpath('h3/a/text()').extract()
      # 同上,p標簽下的 文字內(nèi)容 ‘text()'
      item['desc'] = site.xpath('p[@class="post_item_summary"]/text()').extract()
      items.append(item)
    return items

(4)運行,

scrapy crawl blog # 即可

(5)輸出文件。

        在 settings.py 中進行輸出配置。

# 輸出文件位置
FEED_URI = 'blog.xml'
# 輸出文件格式 可以為 json,xml,csv
FEED_FORMAT = 'xml'

    輸出位置為項目根文件夾下。

二、基本的 -- scrapy.spider.Spider

    (1)使用交互shell

dizzy@dizzy-pc:~$ scrapy shell "http://www.baidu.com/"
2014-08-21 04:09:11+0800 [scrapy] INFO: Scrapy 0.24.4 started (bot: scrapybot)
2014-08-21 04:09:11+0800 [scrapy] INFO: Optional features available: ssl, http11, django
2014-08-21 04:09:11+0800 [scrapy] INFO: Overridden settings: {'LOGSTATS_INTERVAL': 0}
2014-08-21 04:09:11+0800 [scrapy] INFO: Enabled extensions: TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState
2014-08-21 04:09:11+0800 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2014-08-21 04:09:11+0800 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2014-08-21 04:09:11+0800 [scrapy] INFO: Enabled item pipelines: 
2014-08-21 04:09:11+0800 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6024
2014-08-21 04:09:11+0800 [scrapy] DEBUG: Web service listening on 127.0.0.1:6081
2014-08-21 04:09:11+0800 [default] INFO: Spider opened
2014-08-21 04:09:12+0800 [default] DEBUG: Crawled (200) <GET http://www.baidu.com/> (referer: None)
[s] Available Scrapy objects:
[s]  crawler  <scrapy.crawler.Crawler object at 0xa483cec>
[s]  item    {}
[s]  request  <GET http://www.baidu.com/>
[s]  response  <200 http://www.baidu.com/>
[s]  settings  <scrapy.settings.Settings object at 0xa0de78c>
[s]  spider   <Spider 'default' at 0xa78086c>
[s] Useful shortcuts:
[s]  shelp()      Shell help (print this help)
[s]  fetch(req_or_url) Fetch request (or URL) and update local objects
[s]  view(response)  View response in a browser
 
>>> 
  # response.body 返回的所有內(nèi)容
  # response.xpath('//ul/li') 可以測試所有的xpath內(nèi)容
    More important, if you type response.selector you will access a selector object you can use to
query the response, and convenient shortcuts like response.xpath() and response.css() mapping to
response.selector.xpath() and response.selector.css()

        也就是可以很方便的,以交互的形式來查看xpath選擇是否正確。之前是用FireFox的F12來選擇的,但是并不能保證每次都能正確的選擇出內(nèi)容。

        也可使用:

scrapy shell 'http://scrapy.org' --nolog
# 參數(shù) --nolog 沒有日志

    (2)示例

from scrapy import Spider
from scrapy_test.items import DmozItem
 
 
class DmozSpider(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):
    for sel in response.xpath('//ul/li'):
      item = DmozItem()
      item['title'] = sel.xpath('a/text()').extract()
      item['link'] = sel.xpath('a/@href').extract()
      item['desc'] = sel.xpath('text()').extract()
      yield item

    (3)保存文件

        可以使用,保存文件。格式可以 json,xml,csv

scrapy crawl -o 'a.json' -t 'json'

    (4)使用模板創(chuàng)建spider

scrapy genspider baidu baidu.com
 
# -*- coding: utf-8 -*-
import scrapy
 
 
class BaiduSpider(scrapy.Spider):
  name = "baidu"
  allowed_domains = ["baidu.com"]
  start_urls = (
    'http://www.baidu.com/',
  )
 
  def parse(self, response):
    pass

    這段先這樣吧,記得之前5個的,現(xiàn)在只能想起4個來了. :-(

    千萬記得隨手點下保存按鈕。否則很是影響心情的(⊙o⊙)!

三、高級 -- scrapy.contrib.spiders.CrawlSpider

例子

#coding=utf-8
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
import scrapy
 
 
class TestSpider(CrawlSpider):
  name = 'test'
  allowed_domains = ['example.com']
  start_urls = ['http://www.example.com/']
  rules = (
    # 元組
    Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),
    Rule(LinkExtractor(allow=('item\.php', )), callback='pars_item'),
  )
 
  def parse_item(self, response):
    self.log('item page : %s' % response.url)
    item = scrapy.Item()
    item['id'] = response.xpath('//td[@id="item_id"]/text()').re('ID:(\d+)')
    item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()
    item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()
    return item

其他的還有 XMLFeedSpider

  • class scrapy.contrib.spiders.XMLFeedSpider
  • class scrapy.contrib.spiders.CSVFeedSpider
  • class scrapy.contrib.spiders.SitemapSpider

四、選擇器

  >>> from scrapy.selector import Selector
  >>> from scrapy.http import HtmlResponse

    可以靈活的使用 .css() 和 .xpath() 來快速的選取目標數(shù)據(jù)

關(guān)于選擇器,需要好好研究一下。xpath() 和 css() ,還要繼續(xù)熟悉 正則.

    當通過class來進行選擇的時候,盡量使用 css() 來選擇,然后再用 xpath() 來選擇元素的熟悉

五、Item Pipeline

Typical use for item pipelines are:
    • cleansing HTML data # 清除HTML數(shù)據(jù)
    • validating scraped data (checking that the items contain certain fields) # 驗證數(shù)據(jù)
    • checking for duplicates (and dropping them) # 檢查重復(fù)
    • storing the scraped item in a database # 存入數(shù)據(jù)庫
    (1)驗證數(shù)據(jù)

from scrapy.exceptions import DropItem
 
class PricePipeline(object):
  vat_factor = 1.5
  def process_item(self, item, spider):
    if item['price']:
      if item['price_excludes_vat']:
        item['price'] *= self.vat_factor
    else:
      raise DropItem('Missing price in %s' % item)

    (2)寫Json文件

import json
 
class JsonWriterPipeline(object):
  def __init__(self):
    self.file = open('json.jl', 'wb')
  def process_item(self, item, spider):
    line = json.dumps(dict(item)) + '\n'
    self.file.write(line)
    return item

    (3)檢查重復(fù)

from scrapy.exceptions import DropItem
 
class Duplicates(object):
  def __init__(self):
    self.ids_seen = set()
  def process_item(self, item, spider):
    if item['id'] in self.ids_seen:
      raise DropItem('Duplicate item found : %s' % item)
    else:
      self.ids_seen.add(item['id'])
      return item

    至于將數(shù)據(jù)寫入數(shù)據(jù)庫,應(yīng)該也很簡單。在 process_item 函數(shù)中,將 item 存入進去即可了。

相關(guān)文章

  • Python tornado上傳文件的功能

    Python tornado上傳文件的功能

    這篇文章主要介紹了Python tornado上傳文件的功能,代碼分為普通上傳和ajax上傳,通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • python制作機器人的實現(xiàn)方法

    python制作機器人的實現(xiàn)方法

    機器人自動回復(fù)在很多場景中都可以用的上,本文主要介紹了python制作機器人的實現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-06-06
  • PyTorch的nn.Module類的定義和使用介紹

    PyTorch的nn.Module類的定義和使用介紹

    在PyTorch中,nn.Module類是構(gòu)建神經(jīng)網(wǎng)絡(luò)模型的基礎(chǔ)類,所有自定義的層、模塊或整個神經(jīng)網(wǎng)絡(luò)架構(gòu)都需要繼承自這個類,本文介紹PyTorch的nn.Module類的定義和使用介紹,感興趣的朋友一起看看吧
    2024-01-01
  • python編碼最佳實踐之總結(jié)

    python編碼最佳實踐之總結(jié)

    python編碼最佳實踐之總結(jié),幫助大家整理了python編碼最佳實踐的相關(guān)知識點,重點從性能角度出發(fā)對python的一些慣用法做一個簡單總結(jié),感興趣的小伙伴們可以參考一下
    2016-02-02
  • Python實現(xiàn)身份證號碼解析

    Python實現(xiàn)身份證號碼解析

    本文給大家匯總介紹下使用Python實現(xiàn)身份證號碼驗證解析的幾個方法,有需要的小伙伴可以參考下。
    2015-09-09
  • python實現(xiàn)數(shù)組求和與平均值

    python實現(xiàn)數(shù)組求和與平均值

    這篇文章主要介紹了python實現(xiàn)數(shù)組求和與平均值方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • Django DRF路由與擴展功能的實現(xiàn)

    Django DRF路由與擴展功能的實現(xiàn)

    這篇文章主要介紹了Django DRF路由與擴展功能的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-06-06
  • Python實現(xiàn)樹的先序、中序、后序排序算法示例

    Python實現(xiàn)樹的先序、中序、后序排序算法示例

    這篇文章主要介紹了Python實現(xiàn)樹的先序、中序、后序排序算法,結(jié)合具體實例形式分析了Python數(shù)據(jù)結(jié)構(gòu)中樹的定義及常用遍歷、排序操作技巧,需要的朋友可以參考下
    2017-06-06
  • 使用Python中的greenlet包實現(xiàn)并發(fā)編程的入門教程

    使用Python中的greenlet包實現(xiàn)并發(fā)編程的入門教程

    這篇文章主要介紹了使用Python中的greenlet包實現(xiàn)并發(fā)編程的入門教程,Python由于GIL的存在并不能實現(xiàn)真正的多線程并發(fā),greenlet可以做到一個相對的替換方案,需要的朋友可以參考下
    2015-04-04
  • 解決django服務(wù)器重啟端口被占用的問題

    解決django服務(wù)器重啟端口被占用的問題

    今天小編就為大家分享一篇解決django服務(wù)器重啟端口被占用的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07

最新評論