[Python] 纯文本查看 复制代码 import requests
import re
def getHtml(url,object):
hd = {'User-Agent':'Mozilla/5.0','Accept':r'text/html,application/xhtml+xml,*/*'}
try:
response = requests.get(url+object,timeout=10,headers=hd)
response.raise_for_status()
response.encoding = response.apparent_encoding
return response.text
except:
return None
import os
object = input("请输入要查找的目标:")
while True:
num = int(input("计划下载图片数:"))
if num<=0:
print("数量非法,必须重新输入")
else:
break
file_path = "D:/pics"
obj_url = "https://image.baidu.com/search/index?ct=201326592&cl=2&st=-1&lm=-1&nc=1&ie=utf-8&tn=baiduimage&ipn=r&rps=1&pv=&fm=rs5&word="
if not os.path.exists(file_path):
os.mkdir(file_path)
if not os.path.exists(file_path+os.sep+object):
os.mkdir(file_path+os.sep+object)
else:
if len(os.listdir(file_path+os.sep+object)) != 0:
print("文件已存在")
exit()
format_str = r'thumbURL":"(https://[^"]+.jpg)'
text = getHtml(obj_url,object)
if text == None:
print("网址访问异常")
exit()
content = re.findall(format_str,text)
content = iter(content)
for i in range(num):
try:
with open(file_path+os.sep+object+os.sep+str(i)+".jpg",'wb') as f:
respon = requests.get(next(content))
f.write(respon.content)
except:
print("爬虫程序提前结束,已经达到最大搜索上限!")
break |