下載Python www.python.org/downloads/w…html
下載包管理工具 pip pypi.org/project/pip… (Python 2.7.9 + 或 Python 3.4+ 以上版本都自帶 pip 工具。)python
配置環境變量 如圖 注意要配置python的Script目錄才能夠在控制檯使用pipgit
使用pip下載包 pip install ...
github
首先要獲取html頁面信息web
使用Urllib 模塊提供了讀取web頁面數據的接口,咱們能夠像讀取本地文件同樣讀取www和ftp上的數據。正則表達式
def getHtml(url):
page=urllib.urlopen(url)
html=page.read()
return html
複製代碼
獲取圖片 下載到本地windows
首先打開頁面的開發者模式 查看元素 找出要抓取的信息 根據信息寫正則表達式微信
def getImg(html)
reg = r'style="background-image:url\((\/\/.+?)\)\;"'
imgre = re.compile(reg)
#讀取html中符合咱們正則表達式的數據
imglist = re.findall(imgre,html)
複製代碼
循環訪問圖片地址保存到本地app
def getImg(html)
x= 0
for imgurl in imglist:
try:
pic = requests.get("http:" + imgurl, timeout=10)
except requests.exceptions.ConnectionError:
print('error!!')
continue
dir = '../images/'+ str(x) + '.jpg'
fp = open(dir, 'wb')
fp.write(pic.content)
fp.close()
x += 1
複製代碼
最終代碼工具
#coding=utf-8
import re
import urllib
import requests
#獲取頁面信息
def getHtml(url):
#Urllib 模塊提供了讀取web頁面數據的接口,咱們能夠像讀取本地文件同樣讀取www和ftp上的數據。
page=urllib.urlopen(url)
html=page.read()
return html
#獲取圖片並下載
def getImg(html):
#正則篩選信息 下面的正則是根據小紅書本身定義的 若是要抓取其餘的 要自行根據規則修改
reg = r'style="background-image:url\((\/\/.+?)\)\;"'
imgre = re.compile(reg)
#讀取html中符合咱們正則表達式的數據
imglist = re.findall(imgre,html)
print imglist
#循環訪問圖片地址保存到本地
x= 0
for imgurl in imglist:
try:
pic = requests.get("http:" + imgurl, timeout=10)
except requests.exceptions.ConnectionError:
print('error!!')
continue
dir = '../images/'+ str(x) + '.jpg'
fp = open(dir, 'wb')
fp.write(pic.content)
fp.close()
x += 1
if len(imglist) > 0 :
print ('download success!!')
else :
print ('Error!! refresh your web url!!')
# 例如輸入=》"https://www.xiaohongshu.com/discovery/item/592eb73114de411fb5c7a6b0?appinstall=0" 記住輸入時要帶雙引號
url = input('Input url:')
html = getHtml(url)
getImg(html)
複製代碼
目錄結構 下載的圖片放在images
運行 命令行進入src目錄執行 python imagetest.py
注意輸入你要抓取的地址時要加雙引號如圖
下載成功以下顯示:
運行錯誤解決:
若是運行信息出現以下錯誤
從新刷新下地址就好 由於小紅書有個驗證 過了必定日期就要手動驗證下才能訪問地址
從新運行便可
個人GitHub源碼地址:github.com/314172670/p… 有問題能夠私我微信號:ting_1_Z