【发布时间】:2010-12-21 23:29:02
【问题描述】:
Python 是否可以通过任何方式将整个 HTML 页面及其内容(images、css)下载到给定 url 的本地文件夹。并更新本地 html 文件以在本地选择内容。
【问题讨论】:
Python 是否可以通过任何方式将整个 HTML 页面及其内容(images、css)下载到给定 url 的本地文件夹。并更新本地 html 文件以在本地选择内容。
【问题讨论】:
您可以使用urllib 模块下载单个 URL,但这只会返回数据。它不会解析 HTML 并自动下载 CSS 文件和图像等内容。
如果您想下载“整个”页面,您需要解析 HTML 并找到您需要下载的其他内容。您可以使用 Beautiful Soup 之类的东西来解析您检索到的 HTML。
This question 有一些示例代码可以做到这一点。
【讨论】:
您正在寻找的是镜像工具。如果你想要一个 Python,PyPI 列出了spider.py,但我没有这方面的经验。其他人可能会更好,但我不知道 - 我使用'wget',它支持getting the CSS 和图像。这可能是你想要的(引用the manual)
只检索一个 HTML 页面,但使 确保所需的所有元素 要显示的页面,例如 内嵌图像和外部样式 表,也下载了。也使 确保下载的页面引用 下载的链接。
wget -p --convert-links http://www.server.com/dir/page.html
【讨论】:
你可以使用 urllib:
import urllib.request
opener = urllib.request.FancyURLopener({})
url = "http://stackoverflow.com/"
f = opener.open(url)
content = f.read()
【讨论】:
FancyURLopener style of invoking requests is deprecated. Use newer urlopen functions/methods
savePage 下面可以:.html
script、link和img下载javascripts、css和images。
_files的文件夹中。sys.stderr
BeautifulSoup 对象使用 Python 3+ Requests、BeautifulSoup 和其他标准库。
函数savePage 接收url 和filename 保存它的位置。
import os, sys
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
import re
def savePage(url, pagepath='page'):
def soupfindnSave(pagefolder, tag2find='img', inner='src'):
"""saves on specified `pagefolder` all tag2find objects"""
if not os.path.exists(pagefolder): # create only once
os.mkdir(pagefolder)
for res in soup.findAll(tag2find): # images, css, etc..
try:
if not res.has_attr(inner): # check if inner tag (file object) exists
continue # may or may not exist
filename = re.sub('\W+', '', os.path.basename(res[inner])) # clean special chars
fileurl = urljoin(url, res.get(inner))
filepath = os.path.join(pagefolder, filename)
# rename html ref so can move html and folder of files anywhere
res[inner] = os.path.join(os.path.basename(pagefolder), filename)
if not os.path.isfile(filepath): # was not downloaded
with open(filepath, 'wb') as file:
filebin = session.get(fileurl)
file.write(filebin.content)
except Exception as exc:
print(exc, file=sys.stderr)
return soup
session = requests.Session()
#... whatever other requests config you need here
response = session.get(url)
soup = BeautifulSoup(response.text, features="lxml")
pagepath, _ = os.path.splitext(pagepath) # avoid duplicate .html
pagefolder = pagepath+'_files' # page contents
soup = soupfindnSave(pagefolder, 'img', 'src')
soup = soupfindnSave(pagefolder, 'link', 'href')
soup = soupfindnSave(pagefolder, 'script', 'src')
with open(pagepath+'.html', 'wb') as file:
file.write(soup.prettify('utf-8'))
return soup
示例将google.com 保存为google.html 和google_files 文件夹中的内容。 (当前文件夹)
soup = savePage('https://www.google.com', 'google')
【讨论】: