引用 皆我百晓生 小程序回复内容作答:
你可以使用Python中的requests库和BeautifulSoup库来解析网页并获取所需的字段。
首先,你需要安装这两个库。你可以在命令行中使用以下命令来安装它们:
pip install requests
pip install beautifulsoup4
接下来,你可以使用以下代码来实现你的需求:
import requests
from bs4 import BeautifulSoup
from fpdf import FPDF
# 获取页面内容
url = "https://www.lunwendata.com/thesis/List_33_34.html"
response = requests.get(url)
html = response.text
# 使用BeautifulSoup解析页面
soup = BeautifulSoup(html, "html.parser")
# 获取标题
title = soup.find("h3").text
# 获取作者
author = soup.find("span", class_="article-info-author").text
# 获取时间
time = soup.find("span", class_="article-info-time").text
# 获取正文
content = soup.find("div", class_="article-content").text
# 存储到MySQL
# 这里假设你已经安装并配置好了MySQL数据库
import mysql.connector
# 建立数据库连接
conn = mysql.connector.connect(
host="your_host",
user="your_username",
password="your_password",
database="your_database"
)
# 创建游标
cursor = conn.cursor()
# 插入数据
sql = "INSERT INTO your_table (title, author, time, content) VALUES (%s, %s, %s, %s)"
data = (title, author, time, content)
cursor.execute(sql, data)
# 提交事务
conn.commit()
# 关闭游标和连接
cursor.close()
conn.close()
# 生成PDF文件
pdf = FPDF()
pdf.add_page()
# 设置字体和大小
pdf.set_font("Arial", size=12)
# 添加标题
pdf.cell(0, 10, title, ln=True, align="C")
# 添加作者和时间
pdf.cell(0, 10, "Author: {}".format(author), ln=True)
pdf.cell(0, 10, "Time: {}".format(time), ln=True)
# 添加正文
pdf.multi_cell(0, 10, content)
# 保存PDF文件
pdf.output("D:\\{}.pdf".format(title), "F")
请替换代码中的your_host
、your_username
、your_password
、your_database
和your_table
为你自己的MySQL数据库的信息和表名。
此外,代码中使用了fpdf库来生成PDF文件,你可以使用以下命令来安装它:
pip install fpdf
请确保你的机器上已经安装了MySQL数据库和相关驱动。