我的代码非常需要帮助。我试图从一本书中做一个练习,我完全遵循了它。代码有效并下载了图像。但是,下载的所有图像都已损坏。我不知道是什么原因造成的,也不知道我错过了什么。
谢谢。
#! python3
# downloadXkcd.py - Downloads every single XKCD comic.
import requests, os, bs4
url = 'http://xkcd.com'
os.makedirs('xkcd', exist_ok=True)
while not url.endswith('#'):
# 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:
comicUrl = comicElem[0].get('src')
# Download the image.
print('Downloading image %s' %(comicUrl))
res.raise_for_status()
# 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')
您正在向文件写入错误的数据:
对于 res.iter_content(100000( 中的块
res 是网页的数据。您应该使用 url comicUrl 获取图像的数据。我想你忘记了这行:
print('Downloading image %s' %(comicUrl))
res = requests.get('http:' + comicUrl)
注意:我在网址之前添加了http:,因为您要提取的图像网址缺少这个。您应该定义一个函数来检查是否需要添加此架构。