###前提・実現したいこと
以下のブログ記事の参考にPythonスクレイピングで画像をダウンロードしようとしています。下記のコードを実行すると、画像が大量にダウンロードされるのですが、例えば20枚など枚数制限をかけるにはコードをどのように変更すれば良いでしょうか。
###該当のソースコード
python
1# coding: utf-8 2 3import os 4import sys 5import traceback 6from mimetypes import guess_extension 7from time import time, sleep 8from urllib.request import urlopen, Request 9from urllib.parse import quote 10from bs4 import BeautifulSoup 11 12MY_EMAIL_ADDR = 'sample@sample.co.jp' 13 14class Fetcher: 15 def __init__(self, ua=''): 16 self.ua = ua 17 18 def fetch(self, url): 19 req = Request(url, headers={'User-Agent': self.ua}) 20 try: 21 with urlopen(req, timeout=3) as p: 22 b_content = p.read() 23 mime = p.getheader('Content-Type') 24 except: 25 sys.stderr.write('Error in fetching {}\n'.format(url)) 26 sys.stderr.write(traceback.format_exc()) 27 return None, None 28 return b_content, mime 29 30fetcher = Fetcher(MY_EMAIL_ADDR) 31 32def fetch_and_save_img(word): 33 data_dir = 'data/' 34 if not os.path.exists(data_dir): 35 os.makedirs(data_dir) 36 37 for i, img_url in enumerate(img_url_list(word)): 38 sleep(0.1) 39 img, mime = fetcher.fetch(img_url) 40 if not mime or not img: 41 continue 42 ext = guess_extension(mime.split(';')[0]) 43 if ext in ('.jpe', '.jpeg'): 44 ext = '.jpg' 45 if not ext: 46 continue 47 result_file = os.path.join(data_dir, str(i) + ext) 48 with open(result_file, mode='wb') as f: 49 f.write(img) 50 print('fetched', img_url) 51 52 53def img_url_list(word): 54 """ 55 using yahoo (this script can't use at google) 56 """ 57 url = 'http://image.search.yahoo.co.jp/search?n=60&p={}&search.x=1'.format(quote(word)) 58 byte_content, _ = fetcher.fetch(url) 59 structured_page = BeautifulSoup(byte_content.decode('UTF-8'), 'html.parser') 60 img_link_elems = structured_page.find_all('a', attrs={'target': 'imagewin'}) 61 img_urls = [e.get('href') for e in img_link_elems if e.get('href').startswith('http')] 62 img_urls = list(set(img_urls)) 63 return img_urls 64 65if __name__ == '__main__': 66 word = sys.argv[1] 67 fetch_and_save_img(word)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/12/07 01:29