python3抓取異步百度瀑布流動態圖片(二)get、json下載代碼講解

製做解析網址的gethtml

 1 def gethtml(url,postdata):
 2 
 3     header = {'User-Agent':
 4                 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0',
 5                 'Referer':
 6                 'http://image.baidu.com',
 7                 'Host': 'image.baidu.com',
 8                 'Accept': 'text/plain, */*; q=0.01',
 9                 'Accept-Encoding':'gzip, deflate',
10                 'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
11                 'Connection':'keep-alive'}
12 
13     # 解析網頁
14     html_bytes = requests.get(url, headers=header,params = postdata)
15 
16     return html_bytes

 

頭部的構造請參考上一篇博文:python

python3抓取異步百度瀑布流動態圖片(一)查找post並假裝頭方法

分析網址:編程

http://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=gif&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&word=gif&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&pn=30&rn=30&gsm=1e&1472364207674=

分解爲:json

url = 'http://image.baidu.com/search/acjson?' + postdata + lasturl

lasturl爲時間戳,精確到後三位小數的時間戳,構造這個時間戳,後三位小數我就隨機生成一個三位數了:數組

1 import time
2 import random
3 timerandom = random.randint(100,999)
4 nowtime = int(time.time())
5 lasturl = str(nowtime) + str(timerandom) + '='

最後製做postdata:app

 1 # 構造post
 2 postdata = {
 3     'tn':'resultjson_com',
 4     'ipn':'rj',
 5     'ct':201326592,
 6     'is':'',
 7     'fp':'result',
 8     'queryWord': keyword,
 9     'cl': 2,
10     'lm': -1,
11     'ie': 'utf-8',
12     'oe': 'utf-8',
13     'adpicid': '',
14     'st': -1,
15     'z':'',
16     'ic': 0,
17     'word': keyword,
18     's': '',
19     'se': '',
20     'tab': '',
21     'width': '',
22     'height': '',
23     'face': 0,
24     'istype': 2,
25     'qc': '',
26     'nc': 1,
27     'fr': '',
28     'pn': pn,
29     'rn': 30,
30     'gsm': '1e'
31 }

其中頁數pn和搜索關鍵字keywork爲:less

1 # 搜索的關鍵字
2 # keywork = input('請輸入你要查找的關鍵字')
3 keyword = 'gif'
4 
5 # 頁數
6 # pn = int(input('你要抓取多少頁:'))
7 pn = 30

將獲得的信息保存在本地,當全部都保存下來了再去下載圖片:dom

1 # 解析網址
2 contents = gethtml(url,postdata)
3 
4 # 將文件以json的格式保存在json文件夾
5 file = open('../json/' + str(pn) + '.json', 'wb')
6 file.write(contents.content)
7 file.close()

讀取文件夾裏面的全部文件:異步

 1 # 找出文件夾下全部xml後綴的文件
 2 def listfiles(rootdir, prefix='.xml'):
 3     file = []
 4     for parent, dirnames, filenames in os.walk(rootdir):
 5         if parent == rootdir:
 6             for filename in filenames:
 7                 if filename.endswith(prefix):
 8                     file.append(rootdir + '/' + filename)
 9             return file
10         else:
11             pass

遍歷json文件夾,讀取裏面的東西:post

 1 # 找到json文件夾下的全部文件名字
 2 files = listfiles('../json/', '.json')
 3 for filename in files:
 4     print(filename)
 5     # 讀取json獲得圖片網址
 6     doc = open(filename, 'rb')
 7     # ('UTF-8')('unicode_escape')('gbk','ignore')
 8     doccontent = doc.read().decode('utf-8', 'ignore')
 9     product = doccontent.replace(' ', '').replace('\n', '')
10     product = json.loads(product)

查詢字典data:

# 獲得字典data
onefile = product['data']

將字典裏面的圖片網址和圖片名稱放到數組裏面:

製做一個解析頭來解析圖片下載:

 1 def getimg(url):
 2 
 3     # 製做一個專家
 4     opener = urllib.request.build_opener()
 5 
 6     # 打開專家頭部
 7     opener.addheaders = [('User-Agent',
 8                           'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0'),
 9                          ('Referer',
10                           'http://image.baidu.com'),
11                          ('Host', 'image.baidu.com')]
12     # 分配專家
13     urllib.request.install_opener(opener)
14 
15     # 解析img
16     html_img = urllib.request.urlopen(url)
17 
18     return html_img

最後將圖片下載到本地的gif文件夾:

 1 for item in onefile:
 2     try:
 3         pic = getimg(item['thumbURL'])
 4         # 保存地址和名稱
 5         filenamep = '../gif/' + validateTitle(item['fromPageTitleEnc'] + '.gif')
 6         # 保存爲gif
 7         filess = open(filenamep, 'wb')
 8         filess.write(pic.read())
 9         filess.close()
10 
11         # 每一次下載都暫停1-3秒
12         loadimg = random.randint(1, 3)
13         print('圖片' + filenamep + '下載完成')
14         print('暫停' + loadimg + '')
15         time.sleep(loadimg)
16 
17     except Exception as err:
18         print(err)
19         print('暫停' + loadimg + '')
20         time.sleep(loadimg)
21         pass

獲得效果以下:

 本文只是編程,處理這種網址最重要的是思想,思想我寫在上一篇博文:

python3抓取異步百度瀑布流動態圖片(一)查找post並假裝頭方法

思想有了,程序是很簡單的問題而已。

相關文章
相關標籤/搜索