#!/usr/python3
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)"'
img=re.compile(reg)
html=html.decode('utf-8')#python3
imglist=re.findall(img,html)
x = 0
for imgurl in imglist:
urllib.request.urlretrieve(imgurl,'%s.jpg'%x)
x = x+1
html=gethtml("http://news.ifeng.com/a/20161115/50258273_0.shtml")html
print(getimg(html))python
代碼中紅色字體部分均爲Python3.0及以上版本在學到爬蟲是須要注意的若是沒有這些紅色的代碼的話可能會出現一下狀況學習
1.TypeError: cannot use a string pattern on a bytes-like object 這種狀況解決方法就是加上html=html.decode('utf-8')#python3這句代碼字體
2.AttributeError: module 'urllib' has no attribute 'urlopen'這種狀況的解決辦法就是將urllib改爲urllib.request就好了url