爬虫图片数据
import re
import requests
from urllib import error
from bs4 import BeautifulSoup
import osnum = 0
numPicture = 0
file = ''
List = []def Find(url):global Listprint('正在檢測圖片總數,請稍等.....')t = 0i = 1s = 0while t < 1000:Url = url + str(t)try:Result = requests.get(Url, timeout=7)except BaseException:t = t + 60#import pdb;pdb.set_trace()continueelse:result = Result.textpic_url = re.findall('"objURL":"(.*?)",', result, re.S) # 先利用正則表達式找到圖片urls += len(pic_url)if len(pic_url) == 0:#import pdb;pdb.set_trace()breakelse:List.append(pic_url)t = t + 60return sdef recommend(url):Re = []try:html = requests.get(url)except error.HTTPError as e:returnelse:html.encoding = 'utf-8'bsObj = BeautifulSoup(html.text, 'html.parser')div = bsObj.find('div', id='topRS')if div is not None:listA = div.findAll('a')for i in listA:if i is not None:Re.append(i.get_text())return Redef dowmloadPicture(html, keyword):global num# t =0pic_url = re.findall('"objURL":"(.*?)",', html, re.S) # 先利用正則表達式找到圖片urlprint('找到關鍵詞:' + keyword + '的圖片,即將開始下載圖片...')for each in pic_url:print('正在下載第' + str(num + 1) + '張圖片,圖片地址:' + str(each))try:if each is not None:pic = requests.get(each, timeout=7)else:continueexcept BaseException:print('錯誤,當前圖片無法下載')continueelse:string = os.path.join(file, str(num) + '.jpg')fp = open(string, 'wb')fp.write(pic.content)fp.close()num += 1if num >= numPicture:returnif __name__ == '__main__':tm = int(input('請輸入每類圖片的下載數量 '))numPicture = tmline_list = []with open('name.txt', encoding='utf-8') as file:line_list = [k.strip() for k in file.readlines()]#import pdb;pdb.set_trace()for word in line_list:url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&pn='tot = Find(url)Recommend = recommend(url) # 記錄相關推薦print('經過檢測%s類圖片共有%d張' % (word, tot))file = wordy = os.path.exists(file)if y == 1:print('該文件已存在,請重新輸入')file = wordos.mkdir(file)else:os.mkdir(file)t = 0tmp = urlwhile t < numPicture:try:url = tmp + str(t)result = requests.get(url, timeout=10)print(url)except error.HTTPError as e:print('網絡錯誤,請調整網絡后重試')t = t + 60else:dowmloadPicture(result.text, word)t = t + 60numPicture = numPicture + tmprint('任務完成')
總結
- 上一篇: ubuntu18.04下利用deepin
- 下一篇: 如何理解pytorch 卷积里group