前提:
python3.4
windows
作用:通過搜狗的微信搜索接口http://weixin.sogou.com/來搜索相關(guān)微信文章,并將標題及相關(guān)鏈接導入Excel表格中
說明:需xlsxwriter模塊,另程序編寫時間為2017/7/11,以免之后程序無法使用可能是網(wǎng)站做過相關(guān)改變,程序較為簡單,除去注釋40多行。
正題:
思路:打開初始Url --> 正則獲取標題及鏈接 --> 改變page循環(huán)第二步 --> 將得到的標題及鏈接導入Excel
爬蟲的第一步都是先手工操作一遍(閑話)
進入上面提到的網(wǎng)址,如輸入:“圖片識別”,搜索,網(wǎng)址變?yōu)椤癶ttp://weixin.sogou.com/weixin?type=2&query=%E5%9B%BE%E7%89%87%E8%AF%86%E5%88%AB&ie=utf8&s_from=input&_sug_=n&_sug_type_=1&w=01015002&oq=&ri=4&sourceid=sugg&sut=0&sst0=1499778531195&lkt=0%2C0%2C0&p=40040108”標紅為重要參數(shù),type=1時是搜索公眾號,暫且不管,query=‘搜索關(guān)鍵詞',關(guān)鍵詞已經(jīng)被編碼,還有一個隱藏參數(shù)page=1
當你跳到第二頁時可以看到“http://weixin.sogou.com/weixin?oq=&query=%E5%9B%BE%E7%89%87%E8%AF%86%E5%88%AB&_sug_type_=1&sut=0&lkt=0%2C0%2C0&s_from=input&ri=4&_sug_=n&type=2&sst0=1499778531195&page=2&ie=utf8&p=40040108&dp=1&w=01015002&dr=1”
好了,url可以得到了
url = 'http://weixin.sogou.com/weixin?type=2&query='+search+'&page='+str(page)
search是要搜索的關(guān)鍵詞,用quote()編碼即可插入
search = urllib.request.quote(search)
page是用來循環(huán)的
for page in range(1,pagenum+1): url = 'http://weixin.sogou.com/weixin?type=2&query='+search+'&page='+str(page)
完整的url已經(jīng)得到了,接下來訪問url,獲得其中的數(shù)據(jù)(創(chuàng)建opener對象,添加header())
import urllib.request header = ('User-Agent','Mozilla/5.0') opener = urllib.request.build_opener() opener.addheaders = [header] urllib.request.install_opener(opener) data = urllib.request.urlopen(url).read().decode()得到頁面內(nèi)容,采用正則表達獲取相關(guān)數(shù)據(jù)
 import re  finddata = re.compile('<a target="_blank" href="(.*?)" rel="external nofollow" rel="external nofollow" .*?uigs="article_title_.*?">(.*?)</a>').findall(data)  #finddata = [('',''),('','')]通過正則獲取的數(shù)據(jù)中存在干擾項(鏈接:‘a(chǎn)mp;')和無關(guān)項(標題:'<em><...><....></em>'),用replace()解決
 title = title.replace('<em><!--red_beg-->','') title = title.replace('<!--red_end--></em>','') link = link.replace('amp;','')將處理后的標題和鏈接保存在列表中
title_link.append(link) title_link.append(title)
如此搜索的標題和鏈接都得到了,接下來導入Excel
先創(chuàng)建Excel
新聞熱點
疑難解答