python 3.4 所寫爬蟲
僅僅是個demo,以百度圖片首頁圖片為例。能跑出圖片上的圖片;
使用 eclipse pydev 編寫:
from SpiderSimple.HtmLHelper import *import impimport sysimp.reload(sys) #sys.setdefaultencoding('utf-8') html = getHtml('http://image.baidu.com/')try: getImage(html) exit()except Exception as e: print(e) HtmlHelper.py文件
上面的 SpiderSimple是自定義的包名
from urllib.request import urlopen,urlretrieve#正則庫import re#打開網頁def getHtml(url): page = urlopen(url) html = page.read() return html#用正則爬里面的圖片地址 def getImage(Html): try: #reg = r'src="(.+?/.jpg)" class' #image = re.compile(reg) image = re.compile(r'<img[^>]*src[=/"/']+([^/"/']*)[/"/'][^>]*>', re.I) Html = Html.decode('utf-8') imaglist = re.findall(image,Html) x =0 for imagurl in imaglist: #將圖片一個個下載到項目所在文件夾 urlretrieve(imagurl, '%s.jpg' % x) x+=1 except Exception as e: print(e)要注意個大問題,python 默認編碼的問題。
有可能報UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128),錯誤。這個要設置python的默認編碼為utf-8.
設置最好的方式是寫bat文件,
echo offset PYTHONIOENCODING=utf8python -u %1
然后重啟電腦。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林站長站的支持。如果你想了解更多相關內容請查看下面相關鏈接
新聞熱點
疑難解答