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 #打開網頁 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 off set PYTHONIOENCODING=utf8 python -u %1
然后重啟電腦。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
使用PyInstaller將Python代碼打包成獨立可執(zhí)行文件詳細步驟
PyInstaller是一個Python庫,可以將Python應用程序轉換為獨立的可執(zhí)行文件,這篇文章主要給大家介紹了關于使用PyInstaller將Python代碼打包成獨立可執(zhí)行文件的詳細步驟,需要的朋友可以參考下2024-07-07使用Python進行數(shù)據(jù)清洗和預處理的實現(xiàn)代碼
Python作為數(shù)據(jù)科學領域的熱門編程語言,提供了豐富的庫和工具來處理和清洗數(shù)據(jù),本文將介紹如何使用Python進行數(shù)據(jù)清洗和預處理,并提供相應的代碼示例,需要的朋友可以參考下2024-05-05