在這個(gè)周根據(jù)小組進(jìn)度安排埂息,我主要學(xué)習(xí)了Python爬蟲的編寫府蔗,學(xué)習(xí)主要參考:
python實(shí)現(xiàn)簡單爬蟲功能
根據(jù)博客內(nèi)容喷斋,我自己嘗試寫了自己的爬蟲代碼:
獲取整個(gè)頁面數(shù)據(jù)
#coding=utf-8
import urllib.request
def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
return html
html = getHtml("http://tieba.baidu.com/p/2738151262")
print (html)
Urllib 模塊提供了讀取web頁面數(shù)據(jù)的接口
urllib.request.urlopen()方法用于打開一個(gè)URL地址
read()方法用于讀取URL上的數(shù)據(jù)划栓,向getHtml()函數(shù)傳遞一個(gè)網(wǎng)址溪厘,并把整個(gè)頁面下載下來,執(zhí)行程序就會(huì)把整個(gè)網(wǎng)頁打印輸出合搅。
篩選頁面中想要的數(shù)據(jù)
首先需要了解正則表達(dá)式多搀,這是下一步學(xué)習(xí)的基礎(chǔ):
Python正則表達(dá)式指南
import re
import urllib.request
def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
return html
def getImg(html):
reg = r'src="(.+?\.jpg)" pic_ext'
imgre = re.compile(reg)
imglist = re.findall(imgre,html.decode('utf-8'))
return imglist
html = getHtml("http://tieba.baidu.com/p/2460150866")
print (getImg(html))
將頁面篩選的數(shù)據(jù)保存到本地
import urllib.request
import re
def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
return html
def getImg(html):
reg = r'src="(.+?\.jpg)" pic_ext'
imgre = re.compile(reg)
imglist = re.findall(imgre,html.decode('utf-8'))
x = 0
for imgurl in imglist:
urllib.request.urlretrieve(imgurl,'%s.jpg' % x)
x+=1
html = getHtml("http://tieba.baidu.com/p/2460150866")
print (getImg(html))
這只是我們這一次項(xiàng)目開發(fā)的一個(gè)開始過程,相信后面會(huì)越來越深入灾部,相信自己能夠在過程中學(xué)到很多Python的知識(shí)康铭,真正開發(fā)出一個(gè)讓自己滿意的在線評測網(wǎng)站。