對于上一篇的微博OCR提取熱搜的方法顯得十分笨拙脖律,本篇用scrapy干凈利落地解決了問題厦坛。
1. 寫爬蟲爬取熱搜網(wǎng)頁內(nèi)容
微博熱搜頁http://s.weibo.com/top/summary是不需要登陸就可以獲得的望门,但是文本不在html網(wǎng)頁框架中菇晃,而是利用一個(gè)連接新的get得到的html蕉毯,里面包含了內(nèi)容的編碼蹦疑。scrapy新建三連省略了西雀,列出爬蟲主體:
# -*- coding: utf-8 -*-
import scrapy
class WeiboSpiderSpider(scrapy.Spider):
? ? name = 'weibo_spider'
? ? allowed_domains = ['weibo.com']
? ? start_urls = ['http://s.weibo.com/ajax/jsonp/gettopsug?uid=&ref=PC_topsug&url=http://s.weibo.com/top/summary&Mozilla=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0&_cb=STK_15287494731273']
? ? def parse(self, response):
? ? ? ? f=open("weibo.txt","w")
? ? ? ? f.write(response.body)
十分簡潔,下載好的網(wǎng)頁內(nèi)容包含在weibo.txt中必尼。
2. 寫主函數(shù)獲得數(shù)據(jù)內(nèi)容并寫入數(shù)據(jù)庫
思路也一目了然蒋搜,用正則提取出note\num的內(nèi)容,然后將內(nèi)容一并寫入數(shù)據(jù)庫中:
# -*- coding=utf-8-*-
import re
import sqlite3
import time
import scrapy
import os
# 執(zhí)行爬蟲
os.system('scrapy crawl weibo_spider')
# 解析文本并保存文本
f=open("weibo.txt",'r')
contents=f.read()
f.close()
item_contents=re.findall('[\d\w\\\\]+(?=","word")',contents)
nums=re.findall('"num":"\d+"',contents)
mycontent=[]
for item in (item_contents):
? ? content=item.decode('unicode_escape')
? ? mycontent.append(content)? ?
? ? print(content)
mynum=[]
for num in nums:
? ? newnum=re.search('\d+',num).group()
? ? newnum=int(newnum)
? ? mynum.append(newnum)
? ? print(newnum)
# 寫入數(shù)據(jù)庫
cx = sqlite3.connect("E:\ATang\MyDatabase\Weibo.db")
print 'Opened database successfully'
mytime = time.strftime('%Y%m%d',time.localtime(time.time()))
shumu=len(mycontent)
for i in range(0,shumu):
? ? sql = "insert into WeiboRedian(date,note,num)values('%s','%s',%d)" % (mytime,mycontent[i],mynum[i])
? ? cx.execute(sql)
? ? cx.commit()
cx.close()
這個(gè)腳本也十分簡潔判莉,可以看出scrapy在讀取規(guī)則的網(wǎng)絡(luò)數(shù)據(jù)比之前用到的OCR方法好太多了豆挽。關(guān)于腳本內(nèi)容的細(xì)節(jié),可以參考scrapy學(xué)習(xí)筆記中的內(nèi)容券盅。但是前述方法也并非一無是處帮哈,在正則表達(dá)式失效的場合,文本識別技術(shù)或者機(jī)器分類就變得極為重要了锰镀。
如果在主函數(shù)加入時(shí)間循環(huán)娘侍,或者改造成exe運(yùn)行程序用windows系統(tǒng)每天調(diào)用的話咖刃,可以做到讓他每天都能爬取到微博熱點(diǎn)信息并匯成數(shù)據(jù)表,以供語義分析和詞云的制作憾筏。