現階段我們利用urllib模塊,去做最簡單的爬蟲,因為比較簡單,所以直接看代碼就行。主要知識就是通過urllib模塊的各個函數加上正則表達式去完成。
- #encoding:utf-8
- import re
- import urllib
- #利用urllib的urlopen()函數打開一個url地址
- #并讀取所有的html代碼,
- def gethtml(url):
- content=urllib.urlopen(url)
- html=content.read()
- return html
- #根據正則表達式去匹配符合規則的內容
- def geturls(html):
- r=r'data-src="(http://.*?)"'
- alllist=re.findall(r,html)
- return alllist
- #利用urlretrieve()下載文件
- def download(list):
- x=0
- for li in list:
- x=x+1
- urllib.urlretrieve(li,"%s.jpg"%x)
- if __name__ == '__main__':
- #內涵段子
- url = "http://neihanshequ.com/pic/"
- #獲取網頁源碼
- html = gethtml(url)
- #根據一定規則過濾出想要的內容
- list = geturls(html)
- #下載圖片
- download(list)
- print list
本站歡迎任何形式的轉載,但請務必注明出處,尊重他人勞動成果
轉載請注明: 文章轉載自:愛思資源網 http://www.randomwithlife.com/show-18-1109-1.html
轉載請注明: 文章轉載自:愛思資源網 http://www.randomwithlife.com/show-18-1109-1.html