如何使用Python Beautiful Soup完美截图一个网站?
我正在开发一个应用程序,它可以根据一个网站的URL下载这个网站,包括它所依赖的CSS、JS和图片资源。这个应用还会创建一个可以离线使用的网页版本。我主要依赖Beautiful Soup来解析HTML响应文本,遍历所有的外部资源(比如CSS、JS、图片等)并将它们下载到本地。有时候这个过程非常顺利,但有时候又不太好使。
我研究的案例是这个网站。在我离线的——本该正常工作的——网页版本中出现了一些问题:

网页的底部内容先显示出来了。显然,有很多因素可能导致这个问题。不过,从Chrome的检查工具来看,并没有提示缺少任何资源,所以我不太确定问题出在哪里。
不过,当我用这段代码检查Soup生成的HTML时:
with open(os.path.join(save_to_dir, name + '_(Offline)' + '.html'), 'w') as fd:
fd.write(soup.encode('utf-8'))
我发现HTML被修改得太多了。例如,下面是这个网站的实时版本:
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>HALL | Group Chat, Instant Messaging</title>
<meta name="description"
content="Hall is group chat and IM for companies and teams. Available free for the web, desktop and mobile. FREE anytime, anywhere.">
<meta property="og:title" content="Hall"/>
<meta property="og:description" content="Real-time chat & texting for business teams."/>
<meta property="og:image" content="https://d3bkj0l4dzdp7x.cloudfront.net/static-assets/hall_logo_400x200.jpg"/>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
而Soup生成的版本如下:
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<title>HALL | Group Chat, Instant Messaging</title>
<meta content="Hall is group chat and IM for companies and teams. Available free for the web, desktop and mobile. FREE anytime, anywhere." name="description">
<meta content="Hall" property="og:title"/>
<meta content="Real-time chat & texting for business teams." property="og:description"/>
<meta content="https://d3bkj0l4dzdp7x.cloudfront.net/static-assets/hall_logo_400x200.jpg" property="og:image"/>
<meta content="chrome=1" http-equiv="X-UA-Compatible">
以上只是一个例子。我的问题是,如何使用Soup生成一个与实时版本尽量相似的HTML结果呢?
2 个回答
1
比Vincent的回答更详细一点
- 如果你能使用Linux系统,可以用下面的命令来获取网站:
wget --random-wait --no-check-certificate -r -p -e robots=off -U mozilla https://hall.com/
这个命令可以“下载”整个网站。
- 使用BeautifulSoup来处理下载下来的文件
你甚至可以写一个简单的脚本,每天运行一次,保存网站的快照。
提醒一下,千万不要频繁地抓取一个网站哦!
1
在BeautifulSoup中,标签的属性是用字典来存储的。因为字典不使用索引,所以属性的顺序可以是随机的。换句话说,你不能像在其他地方那样依赖顺序来处理这些属性。
一个解决办法是:
- 获取网站内容。
- 把它保存到一个文件里。
- 使用BeautifulSoup来提取源代码和其他内容。
这样,你就可以在文件中得到一个准确的响应副本,而且仍然可以使用BeautifulSoup,速度也不会变慢。