如何使用python实现简单爬取网页数据并导入MySQL中的数据库

前言:要使用 Python 爬取网页数据并将数据导入 MySQL 数据库,您需要使用 Requests 库进行网页抓取,使用 BeautifulSoup 库对抓取到的 HTML 进行解析,并使用 PyMySQL 库与 MySQL 进行交互。

以下是一个简单的示例:
1.  安装所需库:

“`

pip install requests beautifulsoup4 pymysql


“`
2.  导入所需库:

“`

import requests
from bs4 import BeautifulSoup
import pymysql


“`
3.  建立数据库连接:

“`

db = pymysql.connect(
    host='localhost',
    user='root',
    password='password',
    db='mydatabase'
)


“`
这里我们假设您已经在本地搭建了 MySQL 数据库,并创建了一个名为 `mydatabase` 的数据库。您需要根据实际情况修改主机、用户名、密码和数据库名。

4.  使用 Requests 库抓取网页:

“`

url = 'http://www.example.com'
response = requests.get(url)
html = response.text


“`
5.  使用 BeautifulSoup 库解析 HTML:

“`

soup = BeautifulSoup(html, 'html.parser')
data = soup.find_all('a')


“`
6.  使用 PyMySQL 库将数据导入数据库:

“`

cursor = db.cursor()
for item in data:
    title = item.string
    url = item.get('href')
    sql = f"INSERT INTO mytable (title, url) VALUES ('{title}', '{url}')"
    cursor.execute(sql)
db.commit()


“`
这里我们使用了 PyMySQL 库的 `cursor` 方法创建游标,然后遍历解析后的数据,并使用 SQL 语句将数据插入到数据库表中。

完整的示例代码如下:

“`

import requests
from bs4 import BeautifulSoup
import pymysql

# 建立数据库连接
db = pymysql.connect(
    host='localhost',
    user='root',
    password='password',
    db='mydatabase'
)

# 抓取网页
url = 'http://www.example.com'
response = requests.get(url)
html = response.text

# 解析 HTML
soup = BeautifulSoup(html, 'html.parser')
data = soup.find_all('a')

# 将数据导入数据库
cursor = db.cursor()
for item in data:
    title = item.string
    url = item.get('href')
    sql = f"INSERT INTO mytable (title, url) VALUES ('{title}', '{url}')"
    cursor.execute(sql)
db.commit()

# 关闭数据库连接
db.close()

“`
注意,这里示例代码仅为演示使用,并未对 SQL 注入攻击进行防范,请勿直接在生产环境中使用。同时,您也需要根据实际情况修改表名、字段名和 SQL 语句等内容。

这只是单纯的思路,仅供参考。
 

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年6月6日
下一篇 2023年6月6日

相关推荐