上次我們學會了怎么樣爬取百度的列表圖片胁出,速度很快甲锡,但是我覺得不滿意员寇,因為爬取的列表圖片都只是縮略圖片凡壤,點擊進入詳情才是高清圖片勺远。于是我繼續(xù)探索橙喘。
實現(xiàn)的步驟
點擊列表圖片,進入詳情頁面胶逢,我們可以獲取詳情頁的請求地址是
https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E6%98%8E%E6%98%9F&step_word=&hs=0&pn=2&spn=0&di=6752966330&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=2&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=371978350%2C138525231&os=3779051497%2C2039068748&simid=0%2C0&adpicid=0&lpn=0&ln=1785&fr=&fmq=1552974833622_R&fm=result&ic=&s=undefined&hd=&latest=©right=&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F015abf5a92a96aa801219231c32adc.jpg%401280w_1l_2o_100sh.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Bzv55s_z%26e3Bv54_z%26e3BvgAzdH3Fo56hAzdH3FZM3YyMTIdMTI%3D_z%26e3Bip4s&gsm=0&rpstart=0&rpnum=0&islist=&querylist=&force=undefined
又臭又長厅瞎, 這個地址不能直接獲取,也是動態(tài)生成的初坠『汪ぃ可以發(fā)現(xiàn)一些參數(shù)可以在列表圖片的數(shù)據(jù)中獲取,列表圖片的數(shù)據(jù)如下碟刺,這樣把對應(yīng)的數(shù)據(jù)填上就可以了锁保,經(jīng)過我測試發(fā)現(xiàn)只有幾個參數(shù)是必要的。
檢查圖片,復制圖片地址
進入Network -> All爽柒,第一個就是詳情頁請求的響應(yīng)吴菠,
ctrl+f查找剛才復制的地址,注意浩村,地址可能不是完全一致做葵,如果找不到可以刪除一些參數(shù)再找一下,最后發(fā)現(xiàn)圖片地址也可以在js代碼中找到心墅,
這樣獲取詳情頁面響應(yīng)后酿矢,可以正則匹配或者解析html要查找圖片的地址。這樣可以就可以下載百度高清大圖了
實現(xiàn)的代碼
import requests
import re
import time
import os
import urllib.parse
from lxml import etree
import json
page_num=30
photo_dir="D:\\data\\pic\\face\\photo"
def getDetailImage(word):
num=0
url = "https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord={0}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=&latest=©right=&word={0}&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&force=&pn={1}&rn="+str(page_num)+"&gsm=1e&1552975216767="
while num<50:
page_url=url.format(urllib.parse.quote(word),num*page_num)
print(page_url)
response=requests.get(page_url)
regex = re.compile(r'\\(?![/u"])')
json_data=json.loads(regex.sub(r"\\\\", response.text))#問題在于編碼中是\xa0之類的怎燥,當遇到有些 不用轉(zhuǎn)義的\http之類的瘫筐,則會出現(xiàn)以上錯誤
for item in json_data['data']:
try :
params={
"word":word,
"di":item['di'],
"tn":"baiduimagedetail",
"cs":item['cs'],
"os":item['os'],
}
detail_url="http://image.baidu.com/search/detail"
response=requests.get(detail_url,params=params)
selector = etree.HTML(response.text)
pic_url=selector.xpath("http://img[@id='hdFirstImgObj']/@src")[0]
print(pic_url)
name=pic_url.split('/')[-1]
headers={
"Referer":page_url,
}
html=requests.get(pic_url,headers=headers)
with open(os.path.join(word_dir,name),'wb')as f:
f.write(html.content)
except:
pass
num=num+1
if __name__ == "__main__":
word = input("請輸入搜索關(guān)鍵詞(可以是人名,地名等): ")
word_dir=os.path.join(photo_dir,word)
if not os.path.exists(word_dir):
os.mkdir(word_dir)
getDetailImage(word)