您可以使用来自requests 包的响应的text 属性获取URL 的响应内容。
这是一个如何使用requests 包从 URL 获取 HTML 内容的示例。
code.py:
import requests
r = requests.get('https://example.com/')
content = r.text
print(type(content))
print(content)
输出:
<class 'str'>
<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
body {
background-color: #f0f0f2;
margin: 0;
padding: 0;
font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
div {
width: 600px;
margin: 5em auto;
padding: 50px;
background-color: #fff;
border-radius: 1em;
}
a:link, a:visited {
color: #38488f;
text-decoration: none;
}
@media (max-width: 700px) {
body {
background-color: #fff;
}
div {
width: auto;
margin: 0 auto;
border-radius: 0;
padding: 1em;
}
}
</style>
</head>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is established to be used for illustrative examples in documents. You may use this
domain in examples without prior coordination or asking for permission.</p>
<p><a href="http://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
此外,您可以通过在r.encoding 中设置编码来更改编码(例如:r.encoding = 'ISO-8859-1')。如果您更改编码,请求将在您调用r.text 时使用新值r.encoding。
使用requests获取所需URL的HTML内容后,将其分配给msg.html以发送电子邮件中的内容。
代码可以这样更新:
import requests
r = requests.get('https://example.com/')
content = str(r.text)
msg.html = content
mail.send(msg)
参考: