getwrite如何返回html字符串
时间: 2023-12-13 08:03:38 浏览: 33
getwrite 是一个 Python 的函数,用于向 HTTP 响应中写入数据。如果你想返回 HTML 字符串,可以在调用 getwrite 函数之前创建一个字符串变量,然后将 HTML 内容写入该变量,最后将该变量作为 getwrite 函数的参数进行调用。示例代码如下:
```python
from http.server import BaseHTTPRequestHandler
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
html_str = "<html><body><h1>Hello, world!</h1></body></html>"
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(html_str.encode())
```
在这个示例中,我们创建了一个名为 html_str 的字符串变量,其中包含了一个简单的 HTML 页面。然后在 do_GET 方法中,我们使用 send_response 和 send_header 函数设置 HTTP 响应的状态码和头部信息,并使用 end_headers 函数结束头部信息的设置。最后,我们使用 wfile.write 函数将 html_str 变量中的内容写入 HTTP 响应中,并使用 encode 函数将字符串转换为字节流。这样,我们就可以返回一个包含 HTML 内容的 HTTP 响应了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
import requests import re import time #使用requests获取网页源代码 import requests import re import time #获取首页源码 html=requests.get('https://www.kanunu8.com/book3/6879/').content.decode(encoding='gbk') # print(html) #获取所有章节链接 herf=re.findall('',html,re.S) print(herf) start=time.time() for i in herf: #通过链接获取每一章的源码 chapter_html=requests.get('https://www.kanunu8.com/book3/6879/'+i).content.decode(encoding='gbk') # print(chapter_html) title=re.search('size="4">(.*?)<',chapter_html,re.S).group(1)#获取章节名称 content=re.findall('(.*?)',chapter_html,re.S)#获取每一张p标签内的内容,结果返回为列表 content_str="\n".join(content).replace("
","")#列表转为字符串并替换多余符号 with open('动物农场/'+title+'.txt','w',encoding='utf-8') as f: f.write(title) f.write(content_str) end=time.time() print(f'单线程耗时{end-start}')请详细江一下这段代码
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)