修正昨天的下载代码,能指定大体下载数量

 1 import requests
 2 import re
 3 import os
 4 
 5 
 6 text=input("请输入要搜索的关键词:")
 7 sl=int(input("请输入要下载几个30张:"))
 8 if not os.path.exists(text):
 9     os.mkdir(text)
10 # 1.确定网址
11 #url=("http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&fm=index&pos=history&word=%s" %text)
12 
13 start_url = url ="http://image.baidu.com/search/index?ct=201326592%2C503316480&z=%2C&s=&tn=baiduimage&ipn=r&word="+text+"&pn={}&ie=utf-8&oe=utf-8&lm=-1&st=-1&fr=&se=&sme=&width=&height=&face=0&hd=1&latest=0&copyright=0"
14 for k in range(sl): #设置此数 来修改图片的下载数量 2 表示要下载60张
15     url= start_url.format(k * 30)
16     # 2. 解析url 得到网页源代码
17 
18     r = requests.get(url)
19 
20     # ret = r.content #网页源代码 二进制数据
21 
22     ret =r.content.decode() #字符串网页源代码
23 
24     # 3.提取图片链接数据,必须是字符串类型的数据
25     # print (ret)
26     result = re.findall('"objURL":"(.*?)",',ret) # result 是一个列表类型
27     # print (result)
28     # 4.保存图片
29     for i in result:
30         print (i)
31         end = re.search('(jpg|png|gif|jpeg)$', i )
32         if end == None:
33             i=i+".jpg"
34         path = re.sub('/','',i[-10:])
35         try:
36             with open (text+"/%s" % path,"ab") as f:
37                  r = requests.get( i,timeout=3)
38                  f.write(r.content)
39         except Exception as e:
40             print (e)
41 
42 print ("下载完毕 请查阅有关======《%s》======的图片" %(text))

完善了一下昨天的问题一,只能下载30张的问题得到完美解决。本地操作的问题,还待完善,如下载完成,自动打开下载文件夹等问题。

原文地址:https://www.cnblogs.com/bcyczhhb/p/10172427.html