用requests/urllib实现带无版权过滤的谷歌图片搜索参数不生效问题
问题根因
- 无版权过滤参数错误:你使用的
il:cl是已失效的旧版参数,谷歌图片当前可商用无版权过滤的正确参数为sur:fc - 反爬策略触发:你设置的
User-Agent仅填写了Google Chrome,不符合标准浏览器UA格式,谷歌会判定为爬虫请求,自动忽略所有自定义过滤参数,返回默认搜索结果 - 图片链接提取逻辑不稳定:直接对HTML节点字符串做拆分提取链接的方式容错性极差,只要页面结构稍有变动就会提取到错误内容
修复后可正常运行代码
import requests import urllib.request from bs4 import BeautifulSoup from urllib.request import urlopen, Request from urllib.parse import quote # 搜索基础配置 base_url = 'https://google.com/search?q=' search_keyword = 'cat' # 参数说明:tbm=isch 开启图片搜索,isz:m 中等尺寸,sur:fc 无版权可复用 url = base_url + quote(search_keyword) + '&tbm=isch&tbs=isz:m,sur:fc' # 标准Chrome浏览器UA,绕过反爬识别 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36' } html = urlopen(Request(url, headers=headers)) soup = BeautifulSoup(html.read(), 'html.parser') # 过滤无效占位图,提取真实图片链接 img_nodes = soup.find_all('img') valid_img_links = [ img.get('src') for img in img_nodes if img.get('src') and img.get('src').startswith('http') ] # 保存第一张符合过滤规则的图片 if valid_img_links: with open('img1.png', 'wb') as file: resp = requests.get(valid_img_links[0], headers=headers) file.write(resp.content)
额外注意事项
- 搜索关键词如果包含中文、特殊符号,必须用
quote编码后再拼接进URL,否则会出现请求错误 - 如果需要提取高清原图,可查找img节点上的
data-src、data-iurl等属性,这些属性通常存储的是无压缩的原图链接 - 不要短时间内发起大量请求,否则会触发谷歌的人机验证,导致所有请求被拦截
内容的提问来源于stack exchange,提问作者SIUV
相关产品推荐
相关产品推荐

