我们需要requests BeautifulSoup python-docx库:
pip install requests
pip install beautifulsoup4
pip install python-docx
import requests
from bs4 import BeautifulSoup
from docx import Document
def get_webpage_text(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
paragraphs = soup.find_all('p') # 根据网页结构调整选择器,提取文章段落
text_content = ''
for paragraph in paragraphs:
text_content += paragraph.get_text() + '\n'
return text_content
def save_as_word(text_content, output_path):
doc = Document()
lines = text_content.split('\n')
for line in lines:
doc.add_paragraph(line)
doc.save(output_path, encoding='utf-8') # 指定编码为 UTF-8
if __name__ == "__main__":
url = "https://example.com" # 请替换为你想要爬取的网页的URL
output_path = "output.docx" # 保存的Word文件名,根据需要更改
webpage_text = get_webpage_text(url)
save_as_word(webpage_text, output_path)
print("Word文档已生成:", output_path)
要解决中文乱码问题,你可以使用 io
模块将文本内容以 UTF-8
编码写入文件。
但是运行后还会出现中文乱码。
检查后发现网页编码模式“UTF-8
”没错
那就不是编码的问题!
继续检查代码,应该是获取网页文本方法不对,将第7行代码中response.text
换成response.content
。
这也是最常见的解决中文乱码的方式之一,请大家务必记住!!!
改掉之后,获取文本中文正常。
完整代码如下:
import requests
from bs4 import BeautifulSoup
from docx import Document
import io
#获取网页信息
def get_webpage_text(url):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'lxml') # 或者 'html5lib'
paragraphs = soup.find_all('p') # 根据网页结构调整选择器,提取文章段落
text_content = ''
for paragraph in paragraphs:
text_content += paragraph.get_text() + '\n'
return text_content
#保存为word文件
def save_as_word(text_content, output_path):
doc = Document()
lines = text_content.split('\n')
for line in lines:
doc.add_paragraph(line)
with io.open(output_path, 'w', encoding='utf-8') as file: #防止中文乱码
file.write(text_content)
if __name__ == "__main__":
url = "https://*****.htm" # 请替换为你想要爬取的网页的URL
output_path = "C:/***.docx" # 保存的Word文件名,根据需要更改
webpage_text = get_webpage_text(url)
save_as_word(webpage_text, output_path)
print("Word文档已生成:", output_path)
*处理中文乱码的方法:
1、确保网页编码正确: 在获取网页内容时,指定正确的编码。例如,如果网页是以 UTF-8 编码,可以在请求时指定编码。
response = requests.get(url, encoding='utf-8')
2、BeautifulSoup 解析时指定编码: 在使用 BeautifulSoup 解析页面时,指定正确的编码。
soup = BeautifulSoup(response.text, 'html.parser', from_encoding='utf-8')
3、使用正确的编码保存文件: 确保在保存 Word 文档时使用正确的编码。
with io.open(output_path, 'w', encoding='utf-8') as file:
file.write(text_content)
4、检查文档打开时的编码设置: 在使用 Microsoft Word 打开文件时,确保选择正确的编码选项。通常情况下,它会自动检测文件的编码。