基于Beautiful Soup的Python脚本:如何下载谷歌搜索原图
如何下载谷歌图片搜索结果的首张原图?
我编写了一个仅下载谷歌搜索结果中首张图片的脚本,目前已实现基础功能,但只能下载页面显示尺寸的缩略图,无法获取原图。尝试修改图片的HTML尺寸属性后问题仍未解决,求可行的解决方案。
当前代码如下:
def download_image(query): url = f"https://www.google.com/search?q={query}&tbm=isch" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") img_tag = soup.find("img", {"class": "yWs4tf"}) if img_tag is not None: img_link = img_tag.get("src") print(query + ' - Downloading image: ' + img_link) os.mkdir(IMAGE_SAVE_PATH) response = requests.get(img_link) image_bytes = BytesIO(response.content) img = Image.open(image_bytes) img.save(IMAGE_SAVE_PATH + query + '.png') else: print("Couldn't find image for: " + query)
解决方案
问题根源
你当前抓取的yWs4tf类<img>标签的src是谷歌生成的缩略图链接,原图的真实地址并不直接在这个标签里,而是藏在图片对应的跳转链接参数中。
修改后的实现代码
import requests from bs4 import BeautifulSoup import os from io import BytesIO from PIL import Image import urllib.parse IMAGE_SAVE_PATH = "./downloaded_images/" def download_image(query): # 模拟浏览器请求头,避免被谷歌反爬机制拦截 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" } url = f"https://www.google.com/search?q={query}&tbm=isch" response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") # 找到包含原图跳转链接的<a>标签 img_a_tag = soup.find("a", {"class": "wXeWr islib nfEiy"}) if img_a_tag is not None: # 提取<a>标签的href属性 img_href = img_a_tag.get("href") # 解析href中的查询参数,提取原图链接 parsed_href = urllib.parse.urlparse(img_href) query_params = urllib.parse.parse_qs(parsed_href.query) img_link = query_params.get("imgurl", [None])[0] if img_link: print(f"{query} - Downloading original image: {img_link}") # 确保保存目录存在,避免重复创建报错 os.makedirs(IMAGE_SAVE_PATH, exist_ok=True) # 下载原图,携带请求头防止被拦截 img_response = requests.get(img_link, headers=headers) image_bytes = BytesIO(img_response.content) img = Image.open(image_bytes) # 处理文件名非法字符,避免保存失败 safe_query = query.replace("/", "_").replace("\\", "_").replace(":", "_") img.save(f"{IMAGE_SAVE_PATH}{safe_query}.png") else: print(f"Couldn't find original image URL for: {query}") else: print(f"Couldn't find image entry for: {query}")
关键改进点
- 添加请求头:模拟浏览器访问,绕过谷歌的基础反爬拦截,确保能获取完整的页面内容。
- 抓取原图链接:通过定位图片对应的
<a>标签,解析其href参数中的imgurl值,得到真实的原图地址。 - 目录安全处理:使用
os.makedirs(..., exist_ok=True)替代os.mkdir,避免目录已存在时抛出异常。 - 文件名处理:替换查询词中的非法字符,防止保存图片时出现路径错误。
注意事项
谷歌图片的页面结构可能会随时间更新,如果后续类名(如wXeWr islib nfEiy)失效,需要重新查看页面HTML结构,找到对应包含原图跳转链接的标签。
内容的提问来源于stack exchange,提问作者Mateusz Skorupiński
相关产品推荐
相关产品推荐

