您好,登录后才能下订单哦!
在当今互联网时代,图片数据已经成为信息传播的重要组成部分。无论是进行数据分析、机器学习模型训练,还是简单的图片收集,爬取网络图片都是一项非常有用的技能。本文将详细介绍如何使用Python爬取百度图片网站并批量下载图片。
在开始之前,我们需要确保已经安装了必要的Python库。以下是本文中将使用到的主要库:
requests
:用于发送HTTP请求。BeautifulSoup
:用于解析HTML文档。os
:用于创建目录和保存文件。re
:用于正则表达式匹配。你可以通过以下命令安装这些库:
pip install requests beautifulsoup4
在编写爬虫之前,我们需要先了解百度图片网站的结构。打开百度图片网站(https://image.baidu.com/),输入关键词进行搜索,观察URL的变化。
例如,搜索关键词“猫”,URL可能如下:
https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1631234567890_R&pv=&ic=0&nc=1&z=&hd=&latest=©right=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&sid=&word=猫
通过分析URL,我们可以发现以下几个关键参数:
word
:搜索关键词。pn
:页码,用于翻页。rn
:每页显示的图片数量。首先,我们需要编写一个函数来发送HTTP请求并获取页面内容。我们可以使用requests
库来实现这一点。
import requests
def fetch_page(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
else:
print(f"Failed to fetch page: {response.status_code}")
return None
接下来,我们需要解析页面内容并提取图片的URL。我们可以使用BeautifulSoup
库来解析HTML文档,并使用正则表达式来提取图片URL。
from bs4 import BeautifulSoup
import re
def extract_image_urls(html):
soup = BeautifulSoup(html, 'html.parser')
image_urls = []
for script in soup.find_all('script'):
if 'var data =' in script.text:
data = script.text
urls = re.findall(r'"thumbURL":"(.*?)"', data)
image_urls.extend(urls)
return image_urls
有了图片的URL后,我们可以编写一个函数来下载图片并保存到本地。
import os
def download_image(url, save_dir, filename):
if not os.path.exists(save_dir):
os.makedirs(save_dir)
response = requests.get(url)
if response.status_code == 200:
with open(os.path.join(save_dir, filename), 'wb') as f:
f.write(response.content)
print(f"Downloaded {filename}")
else:
print(f"Failed to download {url}")
最后,我们将上述函数整合起来,实现批量下载图片的功能。
def download_baidu_images(keyword, num_images, save_dir):
base_url = "https://image.baidu.com/search/index"
params = {
'tn': 'baiduimage',
'ipn': 'r',
'ct': '201326592',
'cl': '2',
'lm': '-1',
'st': '-1',
'fm': 'result',
'fr': '',
'sf': '1',
'fmq': '1631234567890_R',
'pv': '',
'ic': '0',
'nc': '1',
'z': '',
'hd': '',
'latest': '',
'copyright': '',
'se': '1',
'showtab': '0',
'fb': '0',
'width': '',
'height': '',
'face': '0',
'istype': '2',
'ie': 'utf-8',
'sid': '',
'word': keyword,
'pn': 0,
'rn': 30
}
downloaded_images = 0
while downloaded_images < num_images:
html = fetch_page(base_url, params=params)
if not html:
break
image_urls = extract_image_urls(html)
for url in image_urls:
if downloaded_images >= num_images:
break
filename = f"{keyword}_{downloaded_images + 1}.jpg"
download_image(url, save_dir, filename)
downloaded_images += 1
params['pn'] += params['rn']
if __name__ == "__main__":
keyword = "猫"
num_images = 100
save_dir = "baidu_images"
download_baidu_images(keyword, num_images, save_dir)
将上述代码保存为一个Python文件(例如baidu_image_downloader.py
),然后在终端中运行:
python baidu_image_downloader.py
程序将开始下载指定数量的图片,并保存到baidu_images
目录中。
本文详细介绍了如何使用Python爬取百度图片网站并批量下载图片。通过分析百度图片网站的结构,编写爬虫代码,我们可以轻松地获取大量图片数据。希望本文对你有所帮助,祝你在爬虫的世界中探索愉快!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。