如何用python将html中的数据存储进mysql中,代码怎么写
时间: 2024-04-22 16:22:56 浏览: 10
可以使用Python中的BeautifulSoup和MySQLdb库来实现将HTML中的数据存储到MySQL中。具体代码如下:
```python
import urllib.request
from bs4 import BeautifulSoup
import MySQLdb
# 连接MySQL数据库
db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="test")
# 创建游标
cursor = db.cursor()
# 打开HTML页面并读取数据
url = "http://example.com"
html = urllib.request.urlopen(url).read()
# 解析HTML页面中的数据
soup = BeautifulSoup(html, "html.parser")
data = soup.find_all("div", {"class": "data"})
# 将数据存储到MySQL中
for d in data:
name = d.find("span", {"class": "name"}).text
value = d.find("span", {"class": "value"}).text
query = "INSERT INTO table_name (name, value) VALUES (%s, %s)"
cursor.execute(query, (name, value))
# 提交更改
db.commit()
# 关闭数据库连接
db.close()
```
在上面的代码中,我们首先连接到MySQL数据库并创建游标。然后打开HTML页面并读取数据。接下来,我们使用BeautifulSoup解析HTML页面中的数据,并使用MySQLdb将数据存储到MySQL数据库中。最后,我们提交更改并关闭数据库连接。