<span id="mktg5"></span>

<i id="mktg5"><meter id="mktg5"></meter></i>

        <label id="mktg5"><meter id="mktg5"></meter></label>
        最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
        問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
        當前位置: 首頁 - 科技 - 知識百科 - 正文

        Scrapy教程--某網站前N篇文章抓取

        來源:懂視網 責編:小采 時間:2020-11-27 14:14:16
        文檔

        Scrapy教程--某網站前N篇文章抓取

        Scrapy教程--某網站前N篇文章抓取:一、前3000名人員列表頁 2)分析頁面結構:每一個td都是,一個人員。 第一個small為排名 第二個a標簽是昵稱和用戶名,以及首頁的博客地址。用戶名通過地址截取獲取 第四個small標簽是,博客數量以及積分,通過字符串分離后可以逐個獲取到。 3)代碼:使用x
        推薦度:
        導讀Scrapy教程--某網站前N篇文章抓取:一、前3000名人員列表頁 2)分析頁面結構:每一個td都是,一個人員。 第一個small為排名 第二個a標簽是昵稱和用戶名,以及首頁的博客地址。用戶名通過地址截取獲取 第四個small標簽是,博客數量以及積分,通過字符串分離后可以逐個獲取到。 3)代碼:使用x

        一、前3000名人員列表頁

          2)分析頁面結構:每一個td都是,一個人員。

              第一個small為排名

              第二個a標簽是昵稱和用戶名,以及首頁的博客地址。用戶名通過地址截取獲取

              第四個small標簽是,博客數量以及積分,通過字符串分離后可以逐個獲取到。

          3)代碼:使用xpath獲取標簽及相關的內容,獲取到首頁博客地址后,發送請求。

        def parse(self, response):
        for i in response.xpath("//table[@width='90%']//td"):
        item = CnblogsItem()
        item['top'] = i.xpath(
        "./small[1]/text()").extract()[0].split('.')[-2].strip()
        item['nickName'] = i.xpath("./a[1]//text()").extract()[0].strip()
        item['userName'] = i.xpath(
        "./a[1]/@href").extract()[0].split('/')[-2].strip()
        totalAndScore = i.xpath(
        "./small[2]//text()").extract()[0].lstrip('(').rstrip(')').split(',')
        item['score'] = totalAndScore[2].strip()
        # print(top)
        # print(nickName)
        # print(userName)
        # print(total)
        # print(score)
        # return
        yield scrapy.Request(i.xpath("./a[1]/@href").extract()[0], meta={'page': 1, 'item': item},
        callback=self.parse_page)

        二、各人員博客列表頁

          1)頁面結構:通過分析,每篇博客的a標簽id中都包含“TitleUrl”,這樣就可以獲取到每篇博客的地址了。每頁面地址,加上default.html?page=2,page跟著變動就可以了。

          2)代碼:置頂的文字會去除掉。

        def parse_page(self, response):
        # print(response.meta['nickName'])
        #//a[contains(@id,'TitleUrl')]
        urlArr = response.url.split('default.aspx?')
        if len(urlArr) > 1:
        baseUrl = urlArr[-2]
        else:
        baseUrl = response.url
        list = response.xpath("//a[contains(@id,'TitleUrl')]")
        for i in list:
        item = CnblogsItem()
        item['top'] = int(response.meta['item']['top'])
        item['nickName'] = response.meta['item']['nickName']
        item['userName'] = response.meta['item']['userName']
        item['score'] = int(response.meta['item']['score'])
        item['pageLink'] = response.url
        item['title'] = i.xpath(
        "./text()").extract()[0].replace(u'[置頂]', '').replace('[Top]', '').strip()
        item['articleLink'] = i.xpath("./@href").extract()[0]
        yield scrapy.Request(i.xpath("./@href").extract()[0], meta={'item': item}, callback=self.parse_content)
        if len(list) > 0:
        response.meta['page'] += 1
        yield scrapy.Request(baseUrl + 'default.aspx?page=' + str(response.meta['page']), meta={'page': response.meta['page'], 'item': response.meta['item']}, callback=self.parse_page)

          3)對于每篇博客的內容,這里沒有抓取。也很簡單,分析頁面。繼續發送請求,找到id為cnblogs_post_body的div就可以了。

        def parse_content(self, response):
         content = response.xpath("//div[@id='cnblogs_post_body']").extract()
         item = response.meta['item']if len(content) == 0:
         item['content'] = u'該文章已加密'else:
         item['content'] = content[0]yield item

        三、數據存儲MongoDB

          這一部分沒什么難的。記著安裝pymongo,pip install pymongo。總共有80+萬篇文章。

        from cnblogs.items import CnblogsItemimport pymongoclass CnblogsPipeline(object):def __init__(self):
         client = pymongo.MongoClient(host='127.0.0.1', port=27017)
         dbName = client['cnblogs']
         self.table = dbName['articles']
         self.table.createdef process_item(self, item, spider):if isinstance(item, CnblogsItem):
         self.table.insert(dict(item))return item

        四、代理及Model類

          scrapy中的代理,很簡單,自定義一個下載中間件,指定一下代理ip和端口就可以了。

        def process_request(self, request, spider):
         request.meta['proxy'] = 'http://117.143.109.173:80'

          Model類,存放的是對應的字段。

        class CnblogsItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()# 排名top = scrapy.Field()
         nickName = scrapy.Field()
         userName = scrapy.Field()# 積分score = scrapy.Field()# 所在頁碼地址pageLink = scrapy.Field()# 文章標題title = scrapy.Field()# 文章鏈接articleLink = scrapy.Field()

            # 文章內容
            content = scrapy.Field()

        五、wordcloud詞云分析

          對每個人的文章進行詞云分析,存儲為圖片。wordcloud的使用用,可參考園內文章。

          這里用了多線程,一個線程用來生成分詞好的txt文本,一個線程用來生成詞云圖片。生成詞云大概,1秒一個。

        # coding=utf-8import sysimport jiebafrom wordcloud import WordCloudimport pymongoimport threadingfrom Queue import Queueimport datetimeimport os
        reload(sys)
        sys.setdefaultencoding('utf-8')class MyThread(threading.Thread):def __init__(self, func, args):
         threading.Thread.__init__(self)
         self.func = func
         self.args = argsdef run(self):
         apply(self.func, self.args)# 獲取內容 線程def getTitle(queue, table):for j in range(1, 3001):# start = datetime.datetime.now()list = table.find({'top': j}, {'title': 1, 'top': 1, 'nickName': 1})if list.count() == 0:continuetxt = ''for i in list:
         txt += str(i['title']) + '
        'name = i['nickName']
         top = i['top']
         txt = ' '.join(jieba.cut(txt))
         queue.put((txt, name, top), 1)# print((datetime.datetime.now() - start).seconds)def getImg(queue, word):for i in range(1, 3001):# start = datetime.datetime.now()get = queue.get(1)
         word.generate(get[0])
         name = get[1].replace('<', '').replace('>', '').replace('/', '').replace('\', '').replace('|', '').replace(':', '').replace('"', '').replace('*', '').replace('?', '')
         word.to_file('wordcloudimgs/' + str(get[2]) + '-' + str(name).decode('utf-8') + '.jpg')print(str(get[1]).decode('utf-8') + '	生成成功')# print((datetime.datetime.now() - start).seconds)def main():
         client = pymongo.MongoClient(host='127.0.0.1', port=27017)
         dbName = client['cnblogs']
         table = dbName['articles']
         wc = WordCloud(
         font_path='msyh.ttc', background_color='#ccc', width=600, height=600)if not os.path.exists('wordcloudimgs'):
         os.mkdir('wordcloudimgs')
         threads = []
         queue = Queue()
         titleThread = MyThread(getTitle, (queue, table))
         imgThread = MyThread(getImg, (queue, wc))
         threads.append(imgThread)
         threads.append(titleThread)for t in threads:
         t.start()for t in threads:
         t.join()if __name__ == "__main__":
         main()

        六、完整源碼地址

          

        附:mongodb內存限制windows:

        聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

        文檔

        Scrapy教程--某網站前N篇文章抓取

        Scrapy教程--某網站前N篇文章抓取:一、前3000名人員列表頁 2)分析頁面結構:每一個td都是,一個人員。 第一個small為排名 第二個a標簽是昵稱和用戶名,以及首頁的博客地址。用戶名通過地址截取獲取 第四個small標簽是,博客數量以及積分,通過字符串分離后可以逐個獲取到。 3)代碼:使用x
        推薦度:
        標簽: 文章 教程 3000
        • 熱門焦點

        最新推薦

        猜你喜歡

        熱門推薦

        專題
        Top
        主站蜘蛛池模板: 国产成人免费永久播放视频平台| 国产亚洲精品AAAA片APP| 成人毛片18女人毛片免费96| 国产国产人免费人成成免视频 | 亚洲人成网站影音先锋播放| 免费激情视频网站| 亚洲一区二区三区免费观看| 三年片免费观看大全国语| 亚洲色大成网站www| 亚洲最大av资源站无码av网址| 亚洲国产另类久久久精品小说| 国产免费资源高清小视频在线观看| 免费视频成人片在线观看| a色毛片免费视频| 叮咚影视在线观看免费完整版| 一道本在线免费视频| 牛牛在线精品观看免费正| 国产精品成人亚洲| 免费视频成人国产精品网站| 亚洲第一se情网站| 人妻18毛片a级毛片免费看| 国产成人+综合亚洲+天堂| 男女作爱免费网站| 国产无遮挡色视频免费观看性色| 一级做a爰性色毛片免费| 久久一区二区三区免费| 中文字幕无码免费久久| 无码人妻一区二区三区免费n鬼沢 无码人妻一区二区三区免费看 | 国产日本一线在线观看免费| 久久受www免费人成_看片中文| 69av免费观看| 免费被黄网站在观看| 亚洲国产成人久久综合区| 亚洲伊人久久精品影院| 亚洲av永久无码嘿嘿嘿| 高潮内射免费看片| 无码日韩精品一区二区三区免费 | 国产成人精品亚洲2020| 国产免费MV大全视频网站| 久久久精品2019免费观看| 国产成人啪精品视频免费网|