You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Selenium+Python爬取谷歌图片链接?代码返回None求助

问题:谷歌图片搜索结果链接获取返回全None

我正在做一个项目,需要获取谷歌图片搜索结果里的链接,但打印image_links时数组元素全为None。试过VSCode调试、改用CSS选择器都没解决,用的是Firefox驱动。

我的Python+Selenium代码如下:

from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from tqdm import tqdm
from modules.download_file import download_file
from modules.lsDir import lsDir
import time
from colorama import Fore, Style, init
import os
import base64
from urllib.parse import urlparse


def google_images(driver, name, intAmount):
    for x in lsDir("gg_downloads"):
        os.remove(os.path.join("gg_downloads", x))

    print(f"[*] Opening Google...")
    driver.get(f"https://www.google.com/search?sclient=img&udm=2&q={name}")
    time.sleep(3)

    print(f"[*] Scrolling down...")
    for _ in tqdm(range(intAmount)):
        ActionChains(driver).scroll_by_amount(0, 10000).perform()
        time.sleep(1)

    print(f"[*] Gathering profile photos...")
    image_elements = driver.find_elements(By.CSS_SELECTOR, "div.eA0Zlc img")
    images = []
    for profile in tqdm(image_elements,desc="Gathering Photos"):
        images.append(profile.get_attribute("src"))
    images = images[::2]

    print(f"[*] Gathering links...")
    links = driver.find_elements(By.XPATH, "/html/body/div[3]/div/div[14]/div/div[2]/div[2]/div/div/div/div/div[1]/div/div/div/div[2]/h3/a") 
    image_links = []
    for link in tqdm(links, desc="Gathering Links"):
        image_links.append(link.get_attribute("href"))
    print(image_links)
    print(f"[*] Downloading profile photos...")
    for i, image_url in tqdm(enumerate(images), desc="Downloading Photos", total=len(images)):
        try:
            if image_url.startswith('data:'):
                # Handle data URL
                header, encoded = image_url.split(",", 1)
                content_type = header.split(":")[1].split(";")[0]
                file_extension = content_type.split("/")[-1]
                
                # Decode base64 content
                image_data = base64.b64decode(encoded)
                
                # Save the file
                with open(f"gg_downloads/{i}.{file_extension}", "wb") as f:
                    f.write(image_data)
            else:
                # Handle regular URL
                parsed_url = urlparse(image_url)
                file_extension = os.path.splitext(parsed_url.path)[1]
                if not file_extension:
                    file_extension = '.jpg'  # Default to .jpg if no extension found
                
                download_file(image_url, f"gg_downloads/{i}{file_extension}")
        except Exception as e:
            print(f"Error downloading image {i}: {str(e)}")

if __name__ == "__main__":
    # Make sure you use pip to install stuff.
    from selenium import webdriver
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.service import Service
    from webdriver_manager.firefox import GeckoDriverManager
    #...
    options = Options()
    if settings.headless:
        options.add_argument('-headless')
    service = Service(GeckoDriverManager().install())
    driver = webdriver.Firefox(options=options, service=service)
    google_images(driver, "John Smith", 10)

Firefox驱动初始化代码:

# Imports
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service
from webdriver_manager.firefox import GeckoDriverManager
#...
options = Options()
if settings.headless:
    options.add_argument('-headless')
service = Service(GeckoDriverManager().install())
driver = webdriver.Firefox(options=options, service=service)

解决方案

核心问题分析

  • 绝对XPATH不可靠:你使用的绝对路径完全依赖页面DOM结构,谷歌图片页面频繁更新,结构变动后路径直接失效,无法定位到正确元素。
  • 缺少显式等待:滚动后直接获取元素,部分元素可能未加载完成,导致获取的元素无效,get_attribute("href")返回None。
  • 元素定位错误:谷歌图片的源链接并非直接对应h3/a标签,当前页面的h3仅为缩略图标题,不是图片的源跳转链接。

修改步骤

  1. 改用相对定位:通过图片卡片容器元素定位源链接,使用CSS选择器或相对XPATH,避免依赖不稳定的绝对路径。
  2. 添加显式等待:等待链接元素加载完成后再获取,避免因未加载导致的None值。
  3. 修正链接解析逻辑:谷歌图片的源链接通常存储在元素的data-href属性中,需要解析该属性提取真实链接。

修改后的代码片段

首先导入显式等待模块:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from urllib.parse import parse_qs, urlparse

替换原Gathering links部分的代码:

print(f"[*] Gathering links...")
# 等待图片卡片链接加载完成,用CSS选择器定位所有图片卡片的跳转元素
wait = WebDriverWait(driver, 10)
links = wait.until(EC.presence_of_all_elements_located(
    (By.CSS_SELECTOR, "div.isv-r.PNCib.MSM1fd.BUooTd a")
))

image_links = []
for link in tqdm(links, desc="Gathering Links"):
    # 优先读取data-href属性(谷歌图片存储源链接的常用属性)
    href = link.get_attribute("data-href")
    if not href:
        href = link.get_attribute("href")
    
    if href:
        # 解析data-href中的真实链接(谷歌会将源链接编码在url参数中)
        if "url=" in href:
            parsed = urlparse(href)
            real_url = parse_qs(parsed.query)["url"][0]
            image_links.append(real_url)
        else:
            image_links.append(href)
print(image_links)

额外优化建议

  • 替换固定time.sleep()为显式等待,提升稳定性:
# 替换原有的time.sleep(3)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.eA0Zlc img")))
  • 优化滚动逻辑:滚动至页面底部直到无新内容加载,替代固定次数滚动。

内容的提问来源于stack exchange,提问作者Thomas Haddad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 08:55:55