python有没有办法将整个html页面及其内容(图像,css)下载到给定URL的本地文件夹.并更新本地html文件以在本地选择内容.
Dav*_*ebb 37
您可以使用该urllib模块下载单个URL,但这只会返回数据.它不会解析HTML并自动下载CSS文件和图像等内容.
如果要下载"整个"页面,则需要解析HTML并找到需要下载的其他内容.您可以使用Beautiful Soup之类的东西来解析您检索的HTML.
这个问题有一些示例代码正是这样做的.
And*_*lke 11
您正在寻找的是一种镜像工具.如果你想在Python中使用它,PyPI列出了spider.py,但我对它没有经验.其他人可能会更好,但我不知道 - 我使用'wget',它支持获取CSS和图像.这可能做你想要的(引自手册)
仅检索一个HTML页面,但要确保还要显示页面显示所需的所有元素,例如内嵌图像和外部样式表.还要确保下载的页面引用了下载的链接.
wget -p --convert-links http://www.server.com/dir/page.html
Run Code Online (Sandbox Code Playgroud)
eus*_*iro 11
savePage 如下:.html并下载javascripts,css并images基于标签脚本、链接和img(tags_inner字典键)。_files。sys.stderr使用 Python 3+ Requests、BeautifulSoup和其他标准库。
该函数savePage接收 aurl以及pagepath将其保存在哪里。
import os, sys, re
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
Run Code Online (Sandbox Code Playgroud)
def savePage(url, pagepath='page'):
def savenRename(soup, pagefolder, session, url, tag, inner):
if not os.path.exists(pagefolder): # create only once
os.mkdir(pagefolder)
for res in soup.findAll(tag): # images, css, etc..
if res.has_attr(inner): # check inner tag (file object) MUST exists
try:
filename, ext = os.path.splitext(os.path.basename(res[inner])) # get name and extension
filename = re.sub('\W+', '', filename) + ext # clean special chars from name
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)
session = requests.Session()
#... whatever other requests config you need here
response = session.get(url)
soup = BeautifulSoup(response.text, "html.parser")
path, _ = os.path.splitext(pagepath)
pagefolder = path+'_files' # page contents folder
tags_inner = {'img': 'src', 'link': 'href', 'script': 'src'} # tag&inner tags to grab
for tag, inner in tags_inner.items(): # saves resource files and rename refs
savenRename(soup, pagefolder, session, url, tag, inner)
with open(path+'.html', 'wb') as file: # saves modified html doc
file.write(soup.prettify('utf-8'))
Run Code Online (Sandbox Code Playgroud)
另存google.com为google.html和文件夹内容的示例google_files。(当前文件夹)
savePage('https://www.google.com', 'google')
Run Code Online (Sandbox Code Playgroud)
你可以使用urlib:
import urllib.request
opener = urllib.request.FancyURLopener({})
url = "http://stackoverflow.com/"
f = opener.open(url)
content = f.read()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71675 次 |
| 最近记录: |