小編給大家分享一下python3中requests庫怎么實現多圖片爬取,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
其實爬取圖片和你下載圖片是一個樣子的,都是操作鏈接,也就是url,所以當我們確定要爬取的東西后就要開始尋找url了,所以先打開百度圖片搜一下。
然后使用瀏覽器F12進入開發者模式,或者右鍵檢查元素

注意看xhr,點開觀察有什么不一樣的(如果沒有xhr就在網頁下滑)
第一個是這樣的
第二個是這樣的
注意看,pn是不是是30的倍數,而此時網頁圖片的數量也在增多,發現了這個,進url看一下,首先看原網頁源碼
view-source:http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111121&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E7%BE%8E%E5%A5%B3&oq=%E7%BE%8E%E5%A5%B3&rsp=-1
再看看兩個Requests URL的頁面,發現都是這樣的
不用管他,找我們要的信息,ObjURL,"ObjURL":"http:\/\/image.tianjimedia.com\/uploadimages\/2015\/131\/34\/545szi3x5s84_680x500.jpg"
就是這個,好,現在東西都找到在哪了,寫程序咯
import re
import requests
import os
name=input('輸入文件夾名稱:')
robot='C:/Users/lenovo/Desktop/'+name+'/'
kv={'user-agent':'mozilla/5.0'}
#獲取url對應的源碼頁面
def getHTMLText(url):
try:
r=requests.get(url,timeout=30,headers=kv)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
except:
return ''
#解析url源碼頁面
def parserHTML(html):
#正則表達式為獲取ObjURL
pattern=r'"ObjURL":"(.*?)"'
reg=re.compile(pattern)
urls=re.findall(reg,html)
return urls
#下載圖片
def download(List):
for url in List:
try:
path=robot+url.split('/')[-1]
url=url.replace('\\','')
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding
if not os.path.exists(robot):
os.makedirs(robot)
if not os.path.exists(path):
with open(path,'wb') as f:
f.write(r.content)
f.close()
print(path+' 文件保存成功')
else:
print('文件已經存在')
except:
continue
#通過Requests URL請求到更多的url源碼頁面
def getmoreurl(num,word):
ur=[]
url=r'http://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord={word}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&word={word}&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&cg=girl&pn={pn}&rn=30'
for x in range(1,num+1):
#word為搜索關鍵詞,num為想獲取的頁面數量
u=url.format(word=word,pn=30*x)
ur.append(u)
return ur
def main():
n=int(input('輸入想下載多少張圖片(n*30):'))
word=input('輸入想下載的圖片:')
#初始頁面url
url='http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1499773676062_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word={word}'.format(word=word)
html=getHTMLText(url)
urls=parserHTML(html)
download(urls)
#下面操作獲取的更多頁面圖片
url1=getmoreurl(n,word)
for i in range(n):
html1=getHTMLText(url1[i])
urls1=parserHTML(html1)
download(urls1)
main()看完了這篇文章,相信你對“python3中requests庫怎么實現多圖片爬取”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。