Step1. 事先準(zhǔn)備
工欲善其事必先利其器,小朋友想學(xué)爬蟲,要先開機
- 下載sublime(代碼編輯器),打開dmg包,拖進(jìn)application安裝
- 下載Python(mac一般自帶),按Control+Space打開Spotlight,輸入terminal,打開,(注意加粗的這段話,后面輸入命令都是在打開的terminal里面進(jìn)行),查看版本輸入
python -V
注意V是大寫,這句命令的意思是說,我要看看現(xiàn)在機器上的Python版本,會輸出類似以下內(nèi)容
Python 2.7.10
-
安裝pyquery
pyquery(先大概了解一下)
pyquery 是對 jQuery 的Python實現(xiàn),比起使用正則,要方便得多。文檔:
http://pythonhosted.org//pyquery/api.html下載easy_install:
https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py在terminal中輸入
sudo python2.7 ez_setup.py
sudo easy_install pyquery
Step2. 寫代碼
## import pyquery
from pyquery import PyQuery as pq
import urllib
import sys,time
## set encoding
reload(sys)
sys.setdefaultencoding('utf-8')
def getCnUrl(s):
return urllib.quote(s.encode('gbk'))
## set key word
if len(sys.argv) == 2:
s = sys.argv[1]
else:
s = '采購'
## http call
html = pq(url="http://news.yodao.com/search?q=" + getCnUrl(s) + "&start=0&length=10&s=rank&tl&tr=no_range&keyfrom=search.page")
## extract data
title = []
content = []
href = []
for text in html('h3 a'):
singleTitle = "".join(pq(text).text().split(' '))
if len(sys.argv) == 3:
singleTitle += " (" + pq(text).attr('href') + ")"
title.append(singleTitle)
href.append(pq(text).attr('href'))
for text in html('h3').next('p'):
string = "".join(pq(text).text().split(' '))
content.append(string)
## save 2 file
write = ""
with open('out/' + time.strftime("%Y-%m-%d", time.localtime()) + "_" + s, 'w') as f:
for i in range(0,len(title)):
out = title[i] + '\n' + content[i] + '\n'
f.write(out + "\n")
print(out)
f.close()
-
代碼大概分兩部分:
- 對關(guān)鍵詞進(jìn)行搜索,獲取搜索結(jié)果。
- 對搜索結(jié)果進(jìn)行解析,組成文本。
在了解了大概組成以后,先不研究代碼,目標(biāo)是先運行起來,這時候,打開之前下載的sublime,Command+N創(chuàng)建一個新的文件,將代碼copy進(jìn)去,Command+S保存,(建議保存在個人文件夾下面,或者桌面)保存時新建一個文件夾,保存在新建的文件夾里面,命名為pq.py
在terminal中輸入
python pq.py [可選關(guān)鍵詞]
可選關(guān)鍵詞可填可不填,為爬取的關(guān)鍵詞,默認(rèn)是“采購”,運行以后,terminal中即顯示爬取的內(nèi)容,內(nèi)容也會存儲在當(dāng)期文件夾下的out目錄下。

后續(xù)課程
目前是一個很簡單的關(guān)鍵詞爬取版本,依賴于網(wǎng)站提供的搜索接口。后面可以深入的內(nèi)容有很多,包括斷句,內(nèi)容來源提供,設(shè)置定時任務(wù),推送到手機,微信公眾號的開發(fā)等等,在這之前,我們需要先進(jìn)行以下課程內(nèi)容的學(xué)習(xí):
- Python學(xué)習(xí),了解代碼編寫與修改
- pyquery(jquery)學(xué)習(xí),更加靈活地處理爬取內(nèi)容
- html基礎(chǔ)(DOM)
- Http基礎(chǔ)