【问题标题】:How to have a perfect snapshot of a website using Python Beautiful Soup?如何使用 Python Beautiful Soup 获得网站的完美快照?
【发布时间】:2014-10-23 10:05:56
【问题描述】:

我正在创建一个给定网站 URL 的应用程序,将下载它,包括其依赖的 CSS/JS/Images 资源。它还将创建网络的离线工作版本。我严重依赖 Beautiful Soup 来解析 html 响应文本,迭代其所有外部资源(css/js/images/etc)并在本地下载。它有时工作得很好。有时不要

我的学习案例是this website。我在离线 - 据说 - 网络的工作版本中有这个故障:

页脚首先显示。肯定有很多因素会导致这个麻烦。但是,从没有抱怨任何缺少资源的 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 &amp; 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">

虽然汤的版本如下所示:

<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 &amp; 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 结果?

【问题讨论】:

  • 我看不出 HTML 之间的区别,除了属性顺序。你能指出区别在哪里吗?
  • 请原谅我在这里误导了你 :) 上面的 sn-p 只是一个例子,bsoup 没有创建一个完美的网络快照:我认为它有可能创建一个非离线工作网络版本。

标签: python beautifulsoup


【解决方案1】:

beautifulsoup 中标签的属性由字典保存。而且由于字典不使用索引,因此可以打乱属性。换句话说,使用 bsoup 是不可能做到这一点的。

解决方案是:

  1. 获取网站。
  2. 将其保存在文件中。
  3. 使用 beautifulsoup 获取资源和资料。

有了这个,您将获得您的响应的精确副本作为您的文件,并且仍然可以使用 bsoup 而不会减慢速度。

【讨论】:

  • 正确!发完这个问题,我也想出了结合使用bsoup+本地文件下载的想法。我只需要以某种方式更改离线版本即可引用此本地下载。我会接受你的回答!
【解决方案2】:

只是比文森特的回答详细一点

  1. 要获取网站,如果你可以访问Linux,你可以使用

wget --random-wait --no-check-certificate -r -p -e robots=off -U mozilla https://hall.com/

“下载”整个网站。

  1. 使用 BeautifulSoup 处理本地文件

您甚至可以编写一个简单的 shell 脚本并每天运行它来保存网站的快照。

提醒一下,不要经常抓取网站!

【讨论】:

  • 不错!虽然我认为需要另一个步骤,例如3. Copy web downloaded from #1, and change all external references to locally downloaded resources rom #2。排序... :)
猜你喜欢
  • 2019-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
相关资源
最近更新 更多