我正在使用以下代码使用 Python 保存网页:
import urllib
import sys
from bs4 import BeautifulSoup
url = 'http://www.vodafone.de/privat/tarife/red-smartphone-tarife.html'
f = urllib.urlretrieve(url,'test.html')
问题:此代码将 html 保存为没有 javascript、图像等的基本 html。我想将网页保存为完整的(就像我们在浏览器中有选项一样)
更新:我现在使用以下代码来保存 webapge 的所有 js/images/css 文件,以便它可以保存为完整的网页,但我的输出 html 仍然像基本 html 一样被保存:
import pycurl
import StringIO
c = pycurl.Curl()
c.setopt(pycurl.URL, "http://www.vodafone.de/privat/tarife/red-smartphone-tarife.html")
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.MAXREDIRS, 5)
c.perform()
html = b.getvalue()
#print html
fh = open("file.html", "w")
fh.write(html)
fh.close()
原文由 user1915050 发布,翻译遵循 CC BY-SA 4.0 许可协议
尝试使用 selenium 模拟您的浏览器。此脚本将弹出网页的
save as
对话框。由于文件对话框超出了 selenium 的范围(你如何做也取决于操作系统),你仍然需要弄清楚如何模拟按下 enter 以开始下载。此外,我认为遵循 @Amber 关于获取链接资源的建议可能更简单,因此是更好的解决方案。不过,我认为使用 selenium 是一个很好的起点,因为
br.page_source
将为您提供整个 dom 以及由 javascript 生成的动态内容。