-4
我已经写了一个脚本从xkcd漫画网站下载单个图像。但是脚本通常运行并且不下载任何图像。有什么问题 ?任何帮助,将不胜感激。这里的代码:无法通过python脚本下载图像
#! python3
import requests, os, bs4
url = 'http://xkcd.com' # starting rule
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd
# Download the page
print('Downloading the page %s...' % url)
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text)
# 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()
print('Done.')
请提供包含'a'的HTML相关代码片段,以便您想要下载的图片。 – 2016-07-14 13:32:32