利用Python爬虫网站数据直接导入mysql数据库中

说明:

可能经常出现要爬取某个网站的数据,这时候需要利用爬虫技术来完成,这块主要使用Python来实现。

如何搭建Python环境我上节文章有详细描述:使用Python3.7实现爬虫技术,获取自己想要的网站数据_学无耻境的博客-CSDN博客_python爬虫技术抓取网站数据

(1)导入包

import requests
from bs4 import BeautifulSoup
import re
import pymysql


beautifulsoup是python的一个HTML解析库,可以用它来方便地从网页中提取数据。

(2)发送请求并打印状态码

url = 'https://docs.microsoft.com/zh-cn/sql/mdx/mdx-function-reference-mdx?view=sql-server-2017'
res = requests.get(url)
res.encoding='utf-8'
print(res.status_code)

encoding='utf-8' 里面处理中文乱码

(3)分析网页发现所要的数据在<tbody>标签中

通过beautifulsoup查找到所有的函数以及描述数据

(4)通过正则表达式取出需要的数据

#re匹配需要的数据
pertern = re.compile(r'<a.*?><span data-stu-id="d5ccf-.*?">(.*?)</span>.*?</a>.*?<td><span data-ttu-id="d5ccf-.*?">(.*?)</span>.*?</td>',
    re.S)

生成正则模式

data = str(data)
item = re.findall(pertern, data)

对data进行强制类型转换(转为字符串)

匹配出数据

(5)存入数据库

def create():
    db = pymysql.connect("localhost", "root", "root", "test")#连接数据库 
 
    cursor = db.cursor()
    cursor.execute("DROP TABLE IF EXISTS FUN_TEST")
 
    sql = """CREATE TABLE FUN_TEST (
            ID INT PRIMARY KEY AUTO_INCREMENT,
            NAME CHAR(20),
            DESCRIBE1 CHAR(255))"""
 
    cursor.execute(sql)
 
    db.close()
 
def insert(value):
    db = pymysql.connect("localhost", "root", "root", "test")
 
    cursor = db.cursor()
    sql = "INSERT INTO FUN_TEST(NAME,DESCRIBE1) VALUES (%s, %s)"
    try:
        cursor.execute(sql,value)
        db.commit()
        print('插入数据成功')
    except:
        db.rollback()
        print("插入数据失败")
    db.close()
 
create()  #创建表

首先创建表,如果存在相同名字的表,则删除;再创建表。

插入数据。

(6)源码

#!/usr/bin/python3
import requests
from bs4 import BeautifulSoup
import re
import pymysql
 
def create():
    db = pymysql.connect(host='localhost',user='root',password='root',database='test')#连接数据库 
 
    cursor = db.cursor()
    cursor.execute("DROP TABLE IF EXISTS FUN_TEST")
 
    sql = """CREATE TABLE FUN_TEST (
            ID INT PRIMARY KEY AUTO_INCREMENT,
            NAME CHAR(20),
            DESCRIBE1 CHAR(255))"""
 
    cursor.execute(sql)
 
    db.close()
 
def insert(value):
    db = pymysql.connect(host='localhost',user='root',password='root',database='test')
 
    cursor = db.cursor()
    sql = "INSERT INTO FUN_TEST(NAME,DESCRIBE1) VALUES (%s, %s)"
    try:
        cursor.execute(sql,value)
        db.commit()
        print('插入数据成功')
    except:
        db.rollback()
        print("插入数据失败")
    db.close()
 
create()  #创建表
 
#re匹配需要的数据
pertern = re.compile(r'<a data-linktype="relative-path" href=".*?">(.*?)</a>.*?<td>(.*?)</td>',
    re.S)
url = 'https://docs.microsoft.com/zh-cn/sql/mdx/mdx-function-reference-mdx?view=sql-server-2017'
res = requests.get(url)
res.encoding='utf-8'
print(res.status_code)
soup = BeautifulSoup(res.text, 'html.parser')
data = soup.find_all('tbody')
print(data)
data = str(data)
item = re.findall(pertern, data)
print(item)
for i in item:
    print(i)
    insert(i)

参考网站:

https://blog.csdn.net/Air_RA/article/details/85225712#commentsedit

Python模块Requests的中文乱码问题 - ShengLeQi - 博客园

要使用Python爬取数据并将其写入数据库,您需要使用以下步骤: 1. 安装必要的库:您需要安装Python库来进行爬取数据库连接。例如,requests库用于发出HTTP请求,beautifulsoup4库用于解析HTML,以及MySQLdb或SQLAlchemy库用于连接数据库。 2. 连接数据库:您需要连接您的数据库。如果您使用MySQL数据库,则可以使用MySQLdb库。如果您使用其他类型的数据库,则可以使用适当的库。 3. 爬取数据:您需要使用requests和beautifulsoup4库来爬取数据。您可以使用requests库发出HTTP请求并获取HTML响应。接下来,您可以使用beautifulsoup4库解析HTML并提取所需的数据。 4. 将数据写入数据库:一旦您从网站上抓取了所需的数据,您需要将其插入到数据库。您可以使用MySQLdb或SQLAlchemy库来实现这一点。您需要编写一个SQL查询,然后将数据作为参数插入数据库。 以下是一个示例代码,它使用PythonMySQLdb库从网站爬取书籍数据并将其保存到MySQL数据库: ```python import requests from bs4 import BeautifulSoup import MySQLdb # 连接数据库 db = MySQLdb.connect(host="localhost", user="root", passwd="", db="books") cursor = db.cursor() # 爬取数据 url = "https://www.example.com/books" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") books = soup.find_all("div", class_="book") # 将数据写入数据库 for book in books: title = book.find("h2").text.strip() author = book.find("p", class_="author").text.strip() sql = "INSERT INTO books (title, author) VALUES (%s, %s)" values = (title, author) cursor.execute(sql, values) db.commit() db.close() ``` 请注意,此代码仅供参考,并且需要根据您的具体情况进行更改。
评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值