#!/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/50243265.html")
print(getimg(html))
代碼中紅色字體部分均為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就行了。
