import bs4
import requests
url = 'http://xkcd.com'
os.makedirs('xkcd', exist_ok=True)
while not url.endswith('#'):
print('Downloading page {0}....'.format(url))
try:
res.raise_for_status()
except Exception as exc:
print('This is a problam {0}'.format(exc))
soup = bs4.BeautifulSoup(res.text, 'html.parser')
comicElem = soup.select('#comic img')
if comicElem == []:
print('Could not find comic image.')
else:
try:
comicUrl = 'http:' + comicElem[0].get('src')
print('Downloading image {0}....'.format(comicUrl))
res = requests.get(comicUrl)
except requests.exceptions.MissingSchema:
prevLink = soup.select('a[rel="prev"]')[0]
url = 'http://xkcd.com' + prevLink.get('href')
continue
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(1000000):
imageFile.write(chunk)
imageFile.close()
prevLink = soup.select('a[rel="prev"]')[0]
url = 'http://xkcd.com' + prevLink.get('href')
print('Done......')
python 爬取网站图片 例子
最新推荐文章于 2024-07-12 16:16:27 发布