Python爬取数据:高效存储至MySQL数据库指南
python爬取的内容如何存到mysql

首页 2025-06-12 16:32:26



Python爬取内容并高效存储到MySQL数据库:实战指南 在当今信息爆炸的时代,数据已成为企业决策的重要支撑

    通过网络爬虫技术,我们可以从各大网站获取有价值的数据

    然而,仅仅抓取数据是不够的,如何高效、安全地存储这些数据以供后续分析使用,同样至关重要

    本文将详细介绍如何使用Python爬取网页内容,并将这些数据存储到MySQL数据库中,从而构建一个完整的数据采集与存储流程

     一、环境准备 在开始之前,请确保你已经安装了以下必要的软件和环境: 1.Python:推荐使用Python 3.x版本,因其具备更强大的功能和更好的社区支持

     2.MySQL:安装并配置好MySQL数据库,确保可以创建和访问数据库

     3.库依赖: -`requests`:用于发送HTTP请求,获取网页内容

     -`BeautifulSoup`:用于解析HTML文档,提取所需信息

     -`pymysql`或 `mysql-connector-python`:用于连接和操作MySQL数据库

     你可以通过pip安装这些库: pip install requests beautifulsoup4 pymysql 二、Python爬取网页内容 首先,我们需要编写一个Python脚本来爬取目标网页的内容

    这里以爬取一个简单的网页新闻标题为例

     import requests from bs4 import BeautifulSoup def fetch_webpage(url): try: response = requests.get(url) response.raise_for_status()检查请求是否成功 return response.text except requests.RequestException as e: print(fError fetching the webpage:{e}) return None url = http://example.com/news html_content =fetch_webpage(url) 接下来,使用BeautifulSoup解析HTML内容,提取新闻标题: if html_content: soup = BeautifulSoup(html_content, html.parser) titles= 【】 fortitle_tag in soup.find_all(h2, class_=news-title): 假设新闻标题在class为news-title的

标签内 titles.append(title_tag.get_text(strip=True)) print(titles) 三、配置MySQL数据库 在MySQL中创建一个数据库和相应的表来存储爬取的数据

    例如,创建一个名为`news_db`的数据库和一个名为`news_articles`的表: CREATE DATABASEnews_db; USE news_db; CREATE TABLEnews_articles ( id INT AUTO_INCREMENT PRIMARY KEY, titleVARCHAR(25 NOT NULL, fetched_at TIMESTAMP DEFAULTCURRENT_TIMESTAMP ); 四、连接MySQL数据库并存储数据 接下来,我们使用`pymysql`库连接到MySQL数据库,并将提取的新闻标题存储到`news_articles`表中

     import pymysql def store_in_mysql(titles): connection = pymysql.connect( host=localhost, user=your_mysql_user, password=your_mysql_password, db=news_db, charset=utf8mb4, cursorclass=pymysql.cursors.DictCursor ) try: with connection.cursor() as cursor: for title in titles: sql = INSERT INTOnews_articles (title)VALUES (%s) cursor.execute(sql, (title,)) connection.commit() except pymysql.MySQLError as e: print(fError storing data in MySQL: {e}) connection.rollback() finally: connection.close() if titles: store_in_mysql(titles) 五、完整代码与错误处理 将上述各部分代码整合,形成完整的爬虫脚本,并添加必要的错误处理和日志记录,以提高代码的健壮性和可维护性

     import requests from bs4 import BeautifulSoup import pymysql import logging 配置日志 logging.basicConfig(level=logging.INFO, format=%(asctime)s - %(levelname)s - %(message)s) def fetch_webpage(url): try: response = requests.get(url) response.raise_for_status() return response.text except requests.RequestException as e: logging.error(fError fetching the webpage:{e}) return None def parse_webpage(html_content): soup = BeautifulSoup(html_content, html.parser) titles= 【】 fortitle_tag in soup.find_all(h2, class_=news-title): titles.append(title_tag.get_text(strip=True)) return titles def store_in_mysql(titles): connection = pymysql.connect( host=localhost, user=your_mysql_user, password=your_mysql_password, db=news_db, charset=utf8mb4, cursorclass=pymysql.cursors.DictCursor ) try: with connection.cursor() as cursor: for title in titles: sql =

MySQL连接就这么简单!本地远程、编程语言连接方法一网打尽
还在为MySQL日期计算头疼?这份加一天操作指南能解决90%问题
MySQL日志到底在哪里?Linux/Windows/macOS全平台查找方法在此
MySQL数据库管理工具全景评测:从Workbench到DBeaver的技术选型指南
MySQL密码忘了怎么办?这份重置指南能救急,Windows/Linux/Mac都适用
你的MySQL为什么经常卡死?可能是锁表在作怪!快速排查方法在此
MySQL单表卡爆怎么办?从策略到实战,一文掌握「分表」救命技巧
清空MySQL数据表千万别用错!DELETE和TRUNCATE这个区别可能导致重大事故
你的MySQL中文排序一团糟?记住这几点,轻松实现准确拼音排序!
别再混淆Hive和MySQL了!读懂它们的天壤之别,才算摸到大数据的门道