日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
一名合格的數(shù)據(jù)分析師分享Python網(wǎng)絡(luò)爬蟲二三事(Scrapy自動(dòng)爬蟲)

接上篇《一名合格的數(shù)據(jù)分析師分享Python網(wǎng)絡(luò)爬蟲二三事(綜合實(shí)戰(zhàn)案例)》

五、綜合實(shí)戰(zhàn)案例

3. 利用Scrapy框架爬取

(1)了解Scrapy

Scrapy使用了Twisted異步網(wǎng)絡(luò)庫來處理網(wǎng)絡(luò)通訊。整體架構(gòu)大致如下:

關(guān)于Scrapy的使用方法請參考其官方文檔

(2)Scrapy自動(dòng)爬蟲

前面的實(shí)戰(zhàn)中我們都是通過循環(huán)構(gòu)建URL進(jìn)行數(shù)據(jù)爬取,其實(shí)還有另外一種實(shí)現(xiàn)方式,首先設(shè)定初始URL,獲取當(dāng)前URL中的新鏈接,基于這些鏈接繼續(xù)爬取,直到所爬取的頁面不存在新的鏈接為止。

(a)需求

采用自動(dòng)爬蟲的方式爬取糗事百科文章鏈接與內(nèi)容,并將文章頭部內(nèi)容與鏈接存儲(chǔ)到MySQL數(shù)據(jù)庫中。

(b)分析

A. 怎么提取首頁文章鏈接?

打開首頁后查看源碼,搜索首頁任一篇文章內(nèi)容,可以看到"/article/118123230"鏈接,點(diǎn)擊進(jìn)去后發(fā)現(xiàn)這就是我們所要的文章內(nèi)容,所以我們在自動(dòng)爬蟲中需設(shè)置鏈接包含"article"

B. 怎么提取詳情頁文章內(nèi)容與鏈接

  • 內(nèi)容

打開詳情頁后,查看文章內(nèi)容如下:

分析可知利用包含屬性class且其值為content的div標(biāo)簽可***確定文章內(nèi)容,表達(dá)式如下:

 
 
  1. "http://div[@class='content']/text()"
  • 鏈接

打開任一詳情頁,復(fù)制詳情頁鏈接,查看詳情頁源碼,搜索鏈接如下:

采用以下XPath表達(dá)式可提取文章鏈接。

 
 
  1. ["http://link[@rel='canonical']/@href"] 

(3)項(xiàng)目源碼

A. 創(chuàng)建爬蟲項(xiàng)目

打開CMD,切換到存儲(chǔ)爬蟲項(xiàng)目的目錄下,輸入:

 
 
  1. scrapy startproject qsbkauto

B. 項(xiàng)目結(jié)構(gòu)說明

  • spiders.qsbkspd.py:爬蟲文件
  • items.py:項(xiàng)目實(shí)體,要提取的內(nèi)容的容器,如當(dāng)當(dāng)網(wǎng)商品的標(biāo)題、評論數(shù)等
  • pipelines.py:項(xiàng)目管道,主要用于數(shù)據(jù)的后續(xù)處理,如將數(shù)據(jù)寫入Excel和db等
  • settings.py:項(xiàng)目設(shè)置,如默認(rèn)是不開啟pipeline、遵守robots協(xié)議等
  • scrapy.cfg:項(xiàng)目配置

C. 創(chuàng)建爬蟲

進(jìn)入創(chuàng)建的爬蟲項(xiàng)目,輸入:

 
 
  1. scrapy genspider -t crawl qsbkspd qiushibaie=ke.com(域名)

D. 定義items

 
 
  1. import scrapyclass QsbkautoItem(scrapy.Item):
  2.     # define the fields for your item here like:
  3.     # name = scrapy.Field()
  4.     Link = scrapy.Field()     #文章鏈接
  5.     Connent = scrapy.Field()  #文章內(nèi)容
  6.     pass

E. 編寫爬蟲

  • qsbkauto.py
  •   
      
    1. # -*- coding: utf-8 -*-import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rulefrom qsbkauto.items import QsbkautoItemfrom scrapy.http import Requestclass QsbkspdSpider(CrawlSpider):
    2.   name = 'qsbkspd'
    3.   allowed_domains = ['qiushibaike.com']
    4.   #start_urls = ['http://qiushibaike.com/']
    5.   def start_requests(self):
    6.       i_headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0"}
    7.       yield Request('http://www.qiushibaike.com/',headers=i_headers)
    8.   rules = (
    9.       Rule(LinkExtractor(allow=r'article/'), callback='parse_item', follow=True),
    10.   )
    11.   def parse_item(self, response):
    12.       #i = {}
    13.       #i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()
    14.       #i['name'] = response.xpath('//div[@id="name"]').extract()
    15.       #i['description'] = response.xpath('//div[@id="description"]').extract()
    16.       i = QsbkautoItem()
    17.       i["content"]=response.xpath("http://div[@class='content']/text()").extract()
    18.       i["link"]=response.xpath("http://link[@rel='canonical']/@href").extract()
    19.       return i

pipelines.py

 
 
  1. import MySQLdbimport timeclass QsbkautoPipeline(object):
  2.   def exeSQL(self,sql):
  3.       '''
  4.       功能:連接MySQL數(shù)據(jù)庫并執(zhí)行sql語句
  5.       @sql:定義SQL語句
  6.       '''
  7.       con = MySQLdb.connect(
  8.           host='localhost',  # port
  9.           user='root',       # usr_name
  10.           passwd='xxxx',     # passname
  11.           db='spdRet',       # db_name
  12.           charset='utf8',
  13.           local_infile = 1
  14.           )
  15.       con.query(sql)
  16.       con.commit()
  17.       con.close()
  18.   def process_item(self, item, spider):
  19.       link_url = item['link'][0]
  20.       content_header = item['content'][0][0:10]
  21.       curr_date = time.strftime('%Y-%m-%d',time.localtime(time.time()))
  22.       content_header = curr_date+'__'+content_header
  23.       if (len(link_url) and len(content_header)):#判斷是否為空值
  24.           try:
  25.               sql="insert into qiushi(content,link) values('"+content_header+"','"+link_url+"')"
  26.               self.exeSQL(sql)
  27.           except Exception as er:
  28.               print("插入錯(cuò)誤,錯(cuò)誤如下:")
  29.               print(er)
  30.       else:
  31.           pass
  32.       return item
  • setting.py
  1. 關(guān)閉ROBOTSTXT_OBEY
  2. 設(shè)置USER_AGENT
  3. 開啟ITEM_PIPELINES

F. 執(zhí)行爬蟲

 
 
  1. scrapy crawl qsbkauto --nolog

G. 結(jié)果

【本文是專欄機(jī)構(gòu)“豈安科技”的原創(chuàng)文章,轉(zhuǎn)載請通過微信公眾號(bigsec)聯(lián)系原作者】


新聞名稱:一名合格的數(shù)據(jù)分析師分享Python網(wǎng)絡(luò)爬蟲二三事(Scrapy自動(dòng)爬蟲)
文章網(wǎng)址:http://m.5511xx.com/article/cdseigj.html