python3.4爬蟲demo
python 3.4 所寫爬蟲
僅僅是個demo,以百度圖片首頁圖片為例。能跑出圖片上的圖片;
使用 eclipse pydev 編寫:
from SpiderSimple.HtmLHelper import * import imp import sys imp.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 #打開網(wǎng)頁 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)
,錯誤。這個要設(shè)置python的默認編碼為utf-8.
設(shè)置最好的方式是寫bat文件,
echo off set PYTHONIOENCODING=utf8 python -u %1
然后重啟電腦。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
使用PyInstaller將Python代碼打包成獨立可執(zhí)行文件詳細步驟
PyInstaller是一個Python庫,可以將Python應(yīng)用程序轉(zhuǎn)換為獨立的可執(zhí)行文件,這篇文章主要給大家介紹了關(guān)于使用PyInstaller將Python代碼打包成獨立可執(zhí)行文件的詳細步驟,需要的朋友可以參考下2024-07-07Python輕量級定時任務(wù)調(diào)度APScheduler的使用
Apscheduler是一個基于Quartz的python定時任務(wù)框架,本文主要介紹了Python輕量級定時任務(wù)調(diào)度APScheduler的使用,具有一定的參考價值,感興趣的可以了解一下2024-02-02使用Python3編寫抓取網(wǎng)頁和只抓網(wǎng)頁圖片的腳本
這篇文章主要介紹了使用Python3編寫抓取網(wǎng)頁和只抓網(wǎng)頁圖片的腳本,使用到了urllib模塊,需要的朋友可以參考下2015-08-08使用Python進行數(shù)據(jù)清洗和預處理的實現(xiàn)代碼
Python作為數(shù)據(jù)科學領(lǐng)域的熱門編程語言,提供了豐富的庫和工具來處理和清洗數(shù)據(jù),本文將介紹如何使用Python進行數(shù)據(jù)清洗和預處理,并提供相應(yīng)的代碼示例,需要的朋友可以參考下2024-05-05