一、先上結論:
- 隻要找到每個圖檔對應的連結,就一定能夠下載下傳它。
- 用到的主要函數:
(中文說明文檔連結),request()
(官方文檔連結)。re.findall()
二、再說步驟:
A、How、Where找到圖檔連結?
- 每張圖檔都有自己對應的連結。在浏覽器中,按
,在火狐的F12
或者Chorme的檢視器
。見下邊例子:elements
B、用代碼How把我們想要的連結提取出來呢?
- 使用正規表達式
。.findall()
C、提取出來連結後How下載下傳到本地呢?
-
和open()
函數write()
三、最後案例
"""案例代碼"""
import requests
import re
# 輸入我們的網站位址
url = 'http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&hs=0&pn=2&spn=0&di=181197009070&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=4075680052%2C587526839&os=46658057%2C248100521&simid=0%2C0&adpicid=0&lpn=0&ln=1612&fr=&fmq=1557668430731_R&fm=&ic=undefined&s=undefined&hd=undefined&latest=undefined©right=undefined&se=&sme=&tab=0&width=undefined&height=undefined&
req = requests.get(url) # 用代碼擷取網頁
txt = req.text # req.text : 傳回文本形式url的内容,相當于文本形式的HTML
# 使用正規表達式提取目标連結。具體是先人工看看該網站url的特點,再确定具體的正則pattern
links = re.findall(r'src="(.*2\.jpg)"', txt) # 關于正規表達式見官網 https://docs.python.org/3/library/re.html
for link in links:
req = requests.get(link) # 把提取出來的連結,全部打開
pic = req.content # 并傳回2進制形式的link的非文本部分,相當于2進制形式的HTML非文本部分
path='e:/pictures/baidutupian.jpg' # 假設已經在e盤建立了檔案夾“pictures”
with open(path, 'wb') as f: # 更多見下邊的備注
f.write(pic)
備注:
1.
with open(path, 'wb') as f
wb
:即以二進制的形式進行操作。如果檔案不存在,則建立;如果存在,則先删除(并複寫)已有資料;(附注連結:r、w、a、rb、wb、ab +的差別)
2. 如果是檔案夾不存在,怎麼自動建立?
# 檢測是否存在 e:/picutres,如果存在、略過,否則建立
if not os.path.exist('e:/pictures'):
os.makedirs('e:/pictures')
3. 如果
print(req.text)
裡邊是亂碼怎麼辦?
可以使用
req.encoding = req.apparent_encoding
:自動傳回并使用網頁裡邊的編碼格式,沒有亂碼。