###前提・実現したいこと
自分は様々なものを参考にしながら、beautifulsoup、requestsを用いた、html解析を行い、html内にある画像のurlから、画像をダウンロードするプログラムを書いています。実現したいことは”https://www.google.co.jp/search?q=検索語&tbm=isch”を用いた、google画像検索の結果からは目標の事を達成できるのですが、他のwebサイトでも使えるように汎用性をもたせたいです。
###発生している問題・エラーメッセージ
Traceback (most recent call last): File "forsq.py", line 58, in <module> main() File "forsq.py", line 54, in main save_image(filename, image) UnboundLocalError: local variable 'image' referenced before assignment
###該当のソースコード
python3
1import os,requests,sys,bs4,datetime 2 3#画像のダウンロード 4def download_image(url, timeout = 10): 5 response = requests.get(url, allow_redirects = False, timeout=timeout) 6 if response.status_code != 200: 7 e = Exception("HTTP status: " + response.status_code) 8 raise e 9 10 content_type = response.headers["content-type"] 11 if 'image' not in content_type: 12 e = Exception("content-type: " + content_type) 13 raise e 14 15 return response.content 16 17#画像のファイル名を決める 18def make_filename(base_dir, number, url): 19 ext = os.path.splitext(url)[1] #拡張子の取得 20 filename = number + ext #番号に拡張子をつけてファイル名にする 21 22 fullpath = os.path.join(base_dir, filename) 23 return fullpath 24 25#画像を保存する 26def save_image(filename,image): 27 with open(filename, "wb") as fout: 28 fout.write(image) 29 30now = datetime.datetime.now() 31os.mkdir('./images' + str(now)) 32try: 33 os.mkdir("./images") 34except: 35 pass 36 37#指定したURLのHTMLから画像のURLを抽出し、ダウンロードする 38def main(): 39 URL = input() 40 URLs = [] 41 res = requests.get(URL) 42 soup = bs4.BeautifulSoup(res.text, "lxml") 43 for tag in soup.find_all('img'): 44 URLs.append(tag.get("src")) 45 images_dir = '/Users/user/Downloads/work_space/2017-09-30 16:39:03.632728/images' 46 idx = 0 47 for url in URLs: 48 filename = make_filename(images_dir, str(idx) , url) 49 try: 50 image = download_image(url) 51 except: 52 pass 53 save_image(filename, image) 54 idx += 1 55 56if __name__ == '__main__': 57 main() 58
###試したこと
例外処理を使う事でパスさせようとしました。グローバル変数などにすることも試しました。
###補足情報(言語/FW/ツール等のバージョンなど)
macOS Sierra
python3
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/10/11 14:42