私はこのコードを試していますが、私はオンラインサイトからすべての画像をスクラップする方法を学んでいます。これは本から取得したコードです。プログラムはエラーなくスムーズに実行できますが、コードを実行すると、フォルダ 'xkcd'に保存された画像はありません。私はすでに数時間それを見ているが、私はまだそれを理解することができなかったので、私が見落としているものを援助したいと思う。どんな支援も大歓迎です。Python - ファイルを書き込んだ後にファイルが保存されなかった
import requests, os, bs4
url = 'http://xkcd.com' # starting url
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd
while not url.endswith('1790/'):
# Download the page.
print('Downloading page %s...' % url)
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text,'html.parser')
# Find the URL of the comic image.
comicElem = soup.select('#comic img')
if comicElem == []:
print('Could not find comic image.')
else:
try:
comicUrl = 'http:' + comicElem[0].get('src')
# Download the image.
print('Downloading image %s...' % (comicUrl))
res = requests.get(comicUrl)
res.raise_for_status()
except requests.exceptions.MissingSchema:
# skip this comic
prevLink = soup.select('a[rel="prev"]')[0]
url = 'http://xkcd.com' + prevLink.get('href')
continue
# Save the image to ./xkcd.
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close()
# Get the Prev button's url.
prevLink = soup.select('a[rel="prev"]')[0]
url = 'http://xkcd.com' + prevLink.get('href')
print('Done.')
編集:上記のコードはうまくいきました。
あなたの書式設定が正しいかどうかはわかりません。 'continue'文の後に何も実行されないので、ファイルは保存されません – Dillanm
インデントをチェックできますか?今あなたのファイル書き込みは例外処理の中で、そして 'continue'の後にあります。 – JCVanHamme
このコードが実行しているコードと同じ場合、ファイルの保存は 'MissingSchema'例外が発生した場合にのみ行われます。あなたは 'except'ブロックからそれを移動させなければなりません。 – JCVanHamme