如何爬取数据,并将数据存入mysql中
时间: 2024-06-09 22:04:34 浏览: 9
爬取数据可以使用 Python 中的 requests 和 BeautifulSoup 库,存入 MySQL 中可以使用 Python 中的 pymysql 库。
以下是一个示例代码,用于从网页上获取数据,并将数据存入 MySQL 数据库中:
```python
import requests
from bs4 import BeautifulSoup
import pymysql
# 连接 MySQL 数据库
db = pymysql.connect(host='localhost', user='root', password='password', database='testdb', charset='utf8mb4')
cursor = db.cursor()
# 爬取网页数据
url = 'https://www.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 解析数据
data = []
for item in soup.find_all('div', {'class': 'item'}):
title = item.find('h2').text
content = item.find('p').text
data.append((title, content))
# 将数据存入 MySQL 数据库中
for item in data:
title, content = item
sql = "INSERT INTO news(title, content) VALUES (%s, %s)"
cursor.execute(sql, (title, content))
db.commit()
# 关闭数据库连接
db.close()
```
在这个示例中,我们首先使用 requests 和 BeautifulSoup 库从网页上获取了数据。然后,我们将数据解析并存入一个列表中。最后,我们使用 pymysql 库将数据存入 MySQL 数据库中。
请注意,示例代码中使用的数据库连接信息是示例信息,请根据您自己的实际情况进行修改。