Playwright-based Google Image Crawler, supporting extraction of high-definition original image URLs and batch downloads.
Quick Start
Install Dependencies
pip install playwright aiohttp requests tqdm
playwright install chromium
Basic Usage
import asyncio
from crawler import GoogleImageCrawler
async def main(): async with GoogleImageCrawler() as crawler: # Search for images results = await crawler.search("cute cats", num_images=10)
# 打印结果
for result in results:
print(f"URL: {result.url}")
print(f"Size: {result.width}x{result.height}")
# 下载图片
downloaded = await crawler.download_images(
results,
output_dir="./downloads"
)
asyncio.run(main())
### 同步 API(快速调用)
```python
from crawler import search_images_sync
# 一行代码搜索图片
results = search_images_sync("mountain landscape", num_images=5)
for r in results:
print(r.url)
Core Features
1. Image Search (GoogleImageCrawler.search)
Use Playwright to automate Google Image search and extract original high-definition image URLs.
results = await crawler.search(
keyword="search term", # 搜索关键词
num_images=10, # 获取数量
safe_search=True, # 安全搜索
min_width=None, # 最小宽度过滤
min_height=None # 最小高度过滤
)
2. Image Download (GoogleImageCrawler.download_images)
Asynchronously batch download images, with support for concurrency control.
downloaded = await crawler.download_images(
results=results, # 搜索结果列表
output_dir="./images", # 输出目录
concurrency=3 # 并发数
)
3. Standalone Download Module (ImageDownloader)
More powerful download functionality, with support for thread pool concurrency and progress display.
from downloader import ImageDownloader
downloader = ImageDownloader(
output_dir="./downloads",
concurrent=5,
max_retries=3
)
results = downloader.download_batch(urls)
4. Command-Line Tool
# 从文件下载
python cli.py -f urls.txt -o ./images
# 带参数下载
python cli.py -f urls.txt -c 10 -t 60 -o ./images
# 下载单张图片
python cli.py -u "https://example.com/image.jpg" -o ./images
Usage Examples
Example 1: Basic Search
import asyncio
from crawler import GoogleImageCrawler
async def basic_search():
async with GoogleImageCrawler(headless=True) as crawler:
results = await crawler.search("sunset beach", num_images=5)
print(f"找到 {len(results)} 张图片:")
for i, result in enumerate(results, 1):
print(f"{i}. {result.title[:40] if result.title else 'No title'}")
print(f" URL: {result.url[:70]}...")
print(f" 尺寸: {result.width}x{result.height}")
asyncio.run(basic_search())
Example 2: HD Wallpaper Search (with size filtering)
async def hd_wallpaper_search():
async with GoogleImageCrawler() as crawler:
results = await crawler.search(
"4k wallpaper",
num_images=5,
min_width=1920,
min_height=1080
)
print(f"找到 {len(results)} 张高清图片:")
for result in results:
print(f"✓ {result.width}x{result.height} - {result.url[:60]}...")
asyncio.run(hd_wallpaper_search())
Example 3: Search and Download
async def search_and_download():
async with GoogleImageCrawler() as crawler:
# 搜索
results = await crawler.search("puppy", num_images=10)
print(f"搜索完成,准备下载 {len(results)} 张图片...")
# 下载
downloaded = await crawler.download_images(
results,
output_dir="./downloads",
concurrency=2
)
print(f"下载成功: {len(downloaded)} 张")
for path in downloaded:
print(f" → {path}")
asyncio.run(search_and_download())
Example 4: Use the Standalone Download Module
from downloader import ImageDownloader
# 单独使用下载模块
downloader = ImageDownloader(
output_dir="./downloads",
concurrent=5,
timeout=30,
max_retries=3
)
# 从 URL 列表下载
urls = [
"https://example.com/image1.jpg",
"https://example.com/image2.jpg"
]
results = downloader.download_batch(urls)
# 统计结果
success = len(results['success'])
failed = len(results['failed'])
print(f"成功: {success}, 失败: {failed}")
Example 5: Combined Usage (Recommended)
import asyncio
from crawler import GoogleImageCrawler
from downloader import ImageDownloader
async def combined_workflow():
# 1. 爬取图片 URL
async with GoogleImageCrawler() as crawler:
results = await crawler.search("mountain", num_images=20)
urls = [r.url for r in results]
# 2. 使用 Downloader 下载(支持更多功能)
downloader = ImageDownloader(
output_dir="./mountain_images",
concurrent=5,
max_retries=3
)
with downloader:
results = downloader.download_batch(urls)
# 统计结果
success = len(results['success'])
failed = len(results['failed'])
print(f"成功: {success}/{success + failed}")
asyncio.run(combined_workflow())
Parameter Description
GoogleImageCrawler Initialization Parameters
| Parameter | Type | Default Value | Description |
|---|---|---|---|
headless |
bool | True | Headless mode (does not display the browser window) |
timeout |
int | 30 | Page load timeout (seconds) |
scroll_pause |
float | 1.5 | Scroll interval (seconds) |
max_retries |
int | 3 | Maximum number of retries |
proxy |
str | None | Proxy server address (e.g., "http://proxy:8080") |
search() Method Parameters
| Parameter | Type | Default Value | Description |
|---|---|---|---|
keyword |
str | Required | Search keyword |
num_images |
int | 10 | Number of images to retrieve |
safe_search |
bool | True | Whether to enable safe search |
min_width |
int | None | Minimum image width filter |
min_height |
int | None | Minimum image height filter |
ImageResult Properties
| Property | Type | Description |
|---|---|---|
url |
str | Original high-definition image URL |
thumbnail_url |
str | Thumbnail URL |
title |
str | Image title |
source_url |
str | Source webpage URL |
width |
int | Image width |
height |
int | Image height |
ImageDownloader Initialization Parameters
| Parameter | Type | Default Value | Description |
|---|---|---|---|
output_dir |
str | "./downloads" | Output directory |
timeout |
int | 30 | Request timeout (seconds) |
max_retries |
int | 3 | Maximum number of retries |
concurrent |
int | 5 | Number of concurrent downloads |
headers |
dict | None | Custom request headers |
CLI Parameters
| Parameter | Short Form | Description |
|---|---|---|
--file |
-f |
URL list file path |
--url |
-u |
Single image URL |
--output |
-o |
Output directory |
--concurrent |
-c |
Number of concurrent downloads |
--timeout |
-t |
Timeout (seconds) |
--retries |
-r |
Maximum number of retries |
--limit |
-l |
Limit the number of downloads |
--proxy |
Proxy server address |
Error handling
Common errors and solutions
1. Browser initialization failed
# 错误: BrowserInitError 或 playwright 相关错误
# 解决方案: 确保已安装浏览器
# 运行安装命令
# playwright install chromium
2. Search timeout or page load failure
# 错误: TimeoutError 或页面加载失败
# 解决方案: 增加超时时间或使用代理
async with GoogleImageCrawler(timeout=60) as crawler:
results = await crawler.search("keyword", num_images=10)
3. Image download failed
# 错误: DownloadError 或 HTTP 错误
# 解决方案: 增加重试次数或使用独立下载模块
downloader = ImageDownloader(max_retries=5, timeout=60)
results = downloader.download_batch(urls)
4. IP restricted
# 错误: 频繁出现连接被拒绝或验证码
# 解决方案: 使用代理和增加滚动间隔
async with GoogleImageCrawler(
proxy="http://proxy:8080",
scroll_pause=3.0 # 增加间隔
) as crawler:
results = await crawler.search("keyword", num_images=10)
Exception handling example
import asyncio
from crawler import GoogleImageCrawler
async def safe_search():
try:
async with GoogleImageCrawler() as crawler:
results = await crawler.search("keyword", num_images=10)
return results
except Exception as e:
print(f"搜索失败: {e}")
return []
async def safe_download(crawler, results):
try:
downloaded = await crawler.download_images(
results,
output_dir="./downloads",
concurrency=2
)
return downloaded
except Exception as e:
print(f"下载失败: {e}")
return []
# 使用
asyncio.run(safe_search())
Technical details
Principle of extracting original image URLs
Each image in Google image search results contains a /imgres link:
/imgres?imgurl=https://example.com/original.jpg&imgrefurl=...
The crawler parses the imgurl parameter to obtain the original image address.
Anti-crawling strategies
- Use a normal user User-Agent
- Set a reasonable viewport size (1920x1080)
- Automatically handle Cookie consent pop-ups
- Scroll interval simulates manual operation (1.5 seconds)
- Exponential backoff retry mechanism
File structure
google-image-crawler/
├── crawler.py # 爬虫核心模块 (Playwright + 异步)
├── downloader.py # 图片下载模块 (Requests + 线程池)
├── config.py # 配置管理
├── cli.py # 命令行工具
├── example.py # 使用示例
└── docs/ # 文档
├── architecture.md # 架构设计
├── api-reference.md # API 参考
└── examples.md # 更多示例
Dependencies
- playwright: Browser automation
- aiohttp: Asynchronous HTTP client
- requests: Synchronous HTTP requests
- tqdm: Progress bar display
Notes
- Comply with terms of service: Please comply with Google's terms of service and the target website's robots.txt
- Control frequency: Avoid overly frequent requests; it is recommended to set a reasonable scroll_pause
- Copyright compliance: For commercial use, please confirm image copyright
- Use a proxy: When scraping in large quantities, it is recommended to use a proxy to avoid IP restrictions
- Resource release: Use
async withcontext manager to ensure the browser closes properly
License
MIT