python學習(6):python爬蟲之requests和BeautifulSoup的使用
阿新 • • 發佈:2019-02-20
前言:
Requests庫跟urllib庫的作用相似,都是根據http協議操作各種訊息和頁面。
都說Requests庫比urllib庫好用,我也沒有體會到好在哪兒。
但是,urllib庫有一點不爽的是:urllib.request.urlretrieve(url, localPath)函式在將某些圖片連結儲存到本地時,會出現錯誤:httpError:304 Forbidden
為什麼會出現這個錯誤?查詢網上的說法,大多認為是Header的問題,不過我試了將完整的Header新增進去仍然不行。
本案例用Requests庫替換urllib庫,並用open().write()方法替換掉urllib.request.urlretrieve(url, localPath)方法。
正文:
一,安裝Requests庫
pip3 install requests
安裝後進入python匯入模組測試是否安裝成功
import requests
沒有出錯即安裝成功
二,結合了Requests庫和BeautifulSoup庫的圖片爬蟲程式
''' requests,bs4 ''' import os import requests from bs4 import BeautifulSoup def getHtmlCode(url): # 該方法傳入url,返回url的html的原始碼 headers = { 'User-Agent': 'MMozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0' } r= requests.get(url,headers=headers) r.encoding='UTF-8' page = r.text return page def getImg(page,localPath): # 該方法傳入html的原始碼,經過擷取其中的img標籤,將圖片儲存到本機 if not os.path.exists(localPath): # 新建資料夾 os.mkdir(localPath) soup = BeautifulSoup(page,'html.parser') # 按照html格式解析頁面 imgList = soup.find_all('img') # 返回包含所有img標籤的列表 x = 0 for imgUrl in imgList: # 列表迴圈 print('正在下載:%s'%imgUrl.get('src')) ir = requests.get(imgUrl.get('src')) # open().write()方法原始且有效 open(localPath+'%d.jpg'%x, 'wb').write(ir.content) x+=1 if __name__ == '__main__': url = 'http://www.zhangzishi.cc/20160712mz.html' localPath = 'e:/pythonSpiderFile/img8/' page = getHtmlCode(url) getImg(page,localPath)