Python 3.x 如何将网页下载为.mhtml

Python 3.x 如何将网页下载为.mhtml,python-3.x,nlp,arabic,Python 3.x,Nlp,Arabic,我能够成功地打开URL并将结果页面保存为.html文件。但是,我无法确定如何下载和保存.mhtml(网页,单个文件) 我的代码是: import urllib.parse, time from urllib.parse import urlparse import urllib.request url = ('https://www.example.com') encoded_url = urllib.parse.quote(url, safe='') print(encoded_url)

我能够成功地打开URL并将结果页面保存为.html文件。但是,我无法确定如何下载和保存.mhtml(网页,单个文件)

我的代码是:

import urllib.parse, time
from urllib.parse import urlparse
import urllib.request

url = ('https://www.example.com')

encoded_url = urllib.parse.quote(url, safe='')

print(encoded_url)

base_url = ("https://translate.google.co.uk/translate?sl=auto&tl=en&u=")

translation_url = base_url+encoded_url

print(translation_url)

req = urllib.request.Request(translation_url, headers={'User-Agent': 'Mozilla/6.0'})

print(req)

response = urllib.request.urlopen(req)

time.sleep(15)

print(response)

webContent = response.read()

print(webContent)

f = open('GoogleTranslated.html', 'wb')

f.write(webContent)

print(f)

f.close
我已尝试使用此问题中捕获的详细信息使用wget: 但细节是不完整的(或者我根本无法理解)


在此阶段,任何建议都会有所帮助。

您是否尝试将Selenium与Chrome Webdriver结合使用以保存页面

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.expected_conditions import visibility_of_element_located
from selenium.webdriver.support.ui import WebDriverWait
import pyautogui

URL = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
FILE_NAME = ''

# open page with selenium
# (first need to download Chrome webdriver, or a firefox webdriver, etc)
driver = webdriver.Chrome()
driver.get(URL)


# wait until body is loaded
WebDriverWait(driver, 60).until(visibility_of_element_located((By.TAG_NAME, 'body')))
time.sleep(1)
# open 'Save as...' to save html and assets
pyautogui.hotkey('ctrl', 's')
time.sleep(1)
if FILE_NAME != '':
    pyautogui.typewrite(FILE_NAME)
pyautogui.hotkey('enter')

另存为mhtml,需要添加参数“--将页面另存为mhtml”

options = webdriver.ChromeOptions()
options.add_argument('--save-page-as-mhtml')
driver = webdriver.Chrome(options=options)


使用
wget
时出现了什么错误?我无法确定如何使用在Python中使用的wget案例中提供的语法(选项)。我能够使用wget成功地下载一个html文件,语法为:import wget wget.download(“,”test.html”)。链接问题的唯一答案显示了如何下载页面树,但没有显示如何将其保存为
.mhtml
。我认为用
wget
没有办法做到这一点,但一旦理解了格式,用Python就不难了。基本上,创建一个
email.message.EmailMessage
attach
每个下载的页面元素。@tripleee-我应该指出,我使用了基于浏览器的“另存为”选项,唯一能为我提供真正“脱机”版本页面的选项是“网页,完成”。似乎.mhtml选项也不合适。最后,所有这些都与我试图保存google translate请求的输出有关。您提到的
email.message.EmailMessage
选项在我的情况下有效吗?谢谢。这是作为MHTML容器使用的格式,您保存什么以及它如何有用取决于您。如果你想要一个翻译,你为什么还要关心页面上的其他内容呢?非常好用。非常感谢。必须在python脚本中指定chromdriver的位置,即使我已将其添加到路径中。如何选择另存为类型:网页,单个文件(*.mhml)?