我创建了此代码,以便从特定网站下载图像,仅用于测试网络爬网。我正在尝试从特定范围下载图像,但是无法更改列表中的元素,否则会出现list index out of range
错误。我正在尝试仅下载最近的10张图像,因为它们是最新的漫画。任何帮助深表感谢!
import requests
import os
import bs4
url = 'http://xkcd.com'
os.makedirs('xkcd', exist_ok=True)
while not url.endswith('#'):
print('Downloading page %s...', url)
res = requests.get(url)
res.raise_for_status()
features = "html.parser"
soup = bs4.BeautifulSoup(res.text, features)
comicElem = soup.select('#comic img')
if not comicElem:
print('Could not fine comic image.')
else:
comicUrl = 'http:' + comicElem[0].get('src')
print('Downloading images %s...' % comicUrl)
res = requests.get(comicUrl)
res.raise_for_status()
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close()
prevLink = soup.select('a[rel="prev"]')[0]
url = 'http://xkcd.com' + prevLink.get('href')
print('Done')