下面是一个用 Python 爬取网页信息,并将其存储到 doc 格式文件的示例代码:
import requests
from bs4 import BeautifulSoup
from docx import Document
def scrape_and_save(url, file_name):
# 爬取网页
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
# 创建 docx 文件
document = Document()
# 在 docx 文件中添加爬取到的网页信息
document.add_paragraph(soup.prettify())
# 保存 docx 文件
document.save(file_name)
url = 'https://www.example.com'
file_name = 'example.docx'
scrape_and_save(url, file_name)
这段代码使用了 requests
库来爬取网页,使用 BeautifulSoup
库来解析 HTML 内容,使用 docx
库来创建和保存 docx 文件。
它会爬取给定的 url
地址的网页内容,然后将网页内容添加到一个新的 docx 文件中,最后将这个 docx 文件保存到给定的文件名 file_name
中。
希望这段代码能够帮到你!