用python连接MySQL,用爬虫爬取新闻中的图片保存在哪里
时间: 2025-04-07 15:03:03 浏览: 23
### Python连接MySQL存储爬虫抓取的新闻图片
为了实现Python通过爬虫抓取新闻图片并将其存储到MySQL数据库中,可以按照以下思路完成:
#### 1. 创建数据库和表格
在Navicat Premium或其他工具中创建一个名为`news_images`的数据库,并在其内部建立一张用于存储图片信息的表。假设该表结构如下:
| 字段名 | 类型 | 描述 |
|--------------|--------------|--------------------|
| id | INT | 主键,自增 |
| image_url | VARCHAR(255) | 图片URL地址 |
| local_path | VARCHAR(255) | 图片本地保存路径 |
| news_title | TEXT | 新闻标题 |
此表的设计允许记录每张图片对应的网络链接以及其被下载后的本地位置。
```sql
CREATE TABLE IF NOT EXISTS `images_table` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`image_url` VARCHAR(255),
`local_path` VARCHAR(255),
`news_title` TEXT
);
```
#### 2. 安装必要的库
确保已经安装了所需的第三方库来支持MySQL连接和HTTP请求功能。
```bash
pip install pymysql requests beautifulsoup4
```
#### 3. 编写Python脚本
以下是完整的代码示例,展示如何从网站上提取新闻图片并将它们存储至MySQL数据库的同时也保存到本地磁盘目录下。
```python
import os
import pymysql
from urllib.parse import urlparse
import requests
from bs4 import BeautifulSoup
def save_to_db(image_data, connection):
""" 将图像数据插入到 MySQL 数据库 """
try:
with connection.cursor() as cursor:
sql = "INSERT INTO images_table (image_url, local_path, news_title) VALUES (%s, %s, %s)"
cursor.execute(sql, (image_data['url'], image_data['path'], image_data['title']))
connection.commit()
except Exception as e:
print(f"Error saving to DB: {e}")
def download_image(url, folder="images"):
""" 下载指定 URL 的图片并返回它的文件系统路径"""
response = requests.get(url)
if not os.path.exists(folder):
os.makedirs(folder)
filename = os.path.join(folder, url.split('/')[-1])
with open(filename, 'wb') as f:
f.write(response.content)
return filename
def fetch_news_and_save():
target_website = "http://example.com/news"
headers = {'User-Agent': 'Mozilla/5.0'}
page_content = requests.get(target_website, headers=headers).text
soup = BeautifulSoup(page_content, features='html.parser')
articles = soup.find_all('article')
db_connection = pymysql.connect(
host='localhost',
user='root',
password='password',
database='news_images'
)
for article in articles[:5]: # 只处理前五条新闻作为演示用途
img_tag = article.select_one('.featured-image img')
title_tag = article.select_one('h2 a')
if img_tag and title_tag:
src = img_tag['src']
alt_text = img_tag.get('alt', '')
parsed_src = urlparse(src)
full_img_url = f"{parsed_src.scheme}://{parsed_src.netloc}{parsed_src.path}"
downloaded_file = download_image(full_img_url)
record = {
'url': full_img_url,
'path': downloaded_file,
'title': title_tag.text.strip(),
}
save_to_db(record, db_connection)
fetch_news_and_save()
print("All done!")
```
上述程序实现了以下几个主要目标:
- 使用BeautifulSoup解析HTML文档中的文章节点;
- 提取出每篇文章内的特色图片及其替代文字说明;
- 调用函数download_image将这些远程资源复制下来;
- 把所得的信息连同实际储存的位置一起录入进预先定义好的SQL表里[^1][^2].
注意替换掉其中的 placeholder 值比如用户名密码等敏感字段以适配自己的环境配置.
阅读全文
相关推荐



















