Skip to content

Instantly share code, notes, and snippets.

@kotoripiyopiyo
Created January 24, 2021 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kotoripiyopiyo/b3eaafcd096cd9c868b2c4f3758001d5 to your computer and use it in GitHub Desktop.
Save kotoripiyopiyo/b3eaafcd096cd9c868b2c4f3758001d5 to your computer and use it in GitHub Desktop.
XKCDコミックをひとつずつダウンロードする
#!/usr/bin/env python3
# downloadxkcd.py XKCDコミックをひとつずつダウンロードする
import requests, os, bs4
url = 'http://xkcd.com'
os.makedirs('xkcd', exist_ok=True)
while not url.endswith('#'):
# ページをダウンロードする
print(f'ページ「{url}」をダウンロード中…')
res = requests.get(url)
res.raise_for_status() # 失敗したら例外を起こす
soup = bs4.BeautifulSoup(res.text) #BeautifulSoupオブジェクトを生成
# コミック画像のURLを見つける
comic_elem = soup.select('#comic img')
if comic_elem == []:
print('コミック画像が見つかりませんでした。')
else:
comic_url = 'http:' + comic_elem[0].get('src')
# 画像をダウンロードする
print(f'画像をダウンロード中… {comic_url}')
try:
res = requests.get(comic_url)
res.raise_for_status()
except requests.exceptions.InvalidURL as err:
print(f'{err}:ダウンロードできませんでした→ {comic_url}')
# 画像を./xkcdに保存する
image_file = open(os.path.join('xkcd', os.path.basename(comic_url)), 'wb')
for chunk in res.iter_content(100000):
image_file.write(chunk)
image_file.close()
# PrevボタンのURLを取得する
prev_link = soup.select('a[rel="prev"]')[0]
url = 'http://xkcd.com' + prev_link.get('href')
print('完了')
@kotoripiyopiyo
Copy link
Author

工夫ポイントは、いくつか普通と違うレイアウトのページがあるので、try/exceptを使って、エラー起こしてもプログラムが止まらないようにしたこと。

@kotoripiyopiyo
Copy link
Author

『退屈なことはPythonにやらせよう』11章Webスクレイピングより

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment