
第0步:前提须知
程序需要完成以下任务:
1. 加载XKCD主页。
2. 保存该页的漫画图片。
3. 转入前一张漫画的链接。
4. 重复直到第一张漫画。这意味着代码需要执行以下操作:
1. 利用requests模块下载页面。
2. 利用Beautiful Soup找到页面中漫画图像的URL。
3. 利用iter_ content()下载漫画图像,并保存到硬盘。
4. 找到前一张漫画的URL链接,然后重复。打开一个浏览器的开发者工具,检查XKCD页面上的元素,你会发现下面的内容:
1. 漫画图像文件的URL,由一个<img> 元素的href 属性给出。
2. <img>元愫在<div id="comic">元素之内。
3. Prev按钮有一个 rel HTML属性,值是prev。
4. 第一张漫画的Prev按钮链接到后缀为# URL的XKCD网址,表明没有前一个页面了。
第1步:设计程序
导入模块
import requests, os, bs4
源网址
url = 'https://xkcd.com' # starting url
创建文件夹
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd
循环
while not url.endswith('#'):
程序大纲
#! python3# downloadXkcd.py - Downloads every single XKCD comic.
import requests, os, bs4
url = 'https://xkcd.com' # starting urlos.makedirs('xkcd', exist_ok=True) # store comics in ./xkcdwhile not url.endswith('#'):# Download the page.
# Find the URL of the comic image.
# Download the image.
# Save the image to ./xkcd.
# Get the Prev button's url.
print('Done.')
第2步:下载网页
print('Downloading page %s...' % url)
res = requests.get(url)
res.raise_for_status()soup = bs4.BeautifulSoup(res.text, 'html.parser')
# Download the page.print('Downloading page %s...' % url) #正在下载中res = requests.get(url)res.raise_for_status()soup = bs4.BeautifulSoup(res.text, 'html.parser')
第3步:寻找和下载漫画图像
# Find the URL of the comic image.comicElem = soup.select('#comic img')if comicElem == []:print('Could not find comic image.')else:comicUrl = 'https:' + comicElem[0].get('src')# Download the image.print('Downloading image %s...' % (comicUrl))res = requests.get(comicUrl)res.raise_for_status()
第4步:保存图像,找到前一张漫画
保存图像
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000): imageFile.write(chunk) imageFile.close()
保存图像的完整代码
# 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 = 'https://xkcd.com' + prevLink.get('href')
程序输出
第5步:类似程序的想法
-
顺着网站的所有链接备份整个网站。 -
复制一个论坛的所有信息。 -
复制一个在线商店中所有产品的目录。

