You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python Selenium无法获取谷歌搜索resultStats元素文本求助

Fixing Selenium to Grab Google's resultStats Text

Hey there! I know you've spent a couple hours troubleshooting this, let's get it sorted out. The main issues with your current code are likely missing waits for elements to load and an incomplete search submission. Here's a step-by-step fix:

Key Issues in Your Original Code

  • Google's search results don't load instantly—if you try to grab resultStats right after sending keys, the element won't exist yet, causing a NoSuchElementException.
  • Your ActionChains code was cut off, and submitting the search can be done more reliably with a simple ENTER key press.
  • Double-check your ChromeDriver path to avoid path escape issues on Windows.

Full Working Code

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Initialize Chrome (use raw string for path to avoid escape issues)
driver = webdriver.Chrome(r'.\chromedriver.exe')
driver.get('https://www.google.de')

# Find search box, input query, and submit search
search_box = driver.find_element(By.ID, 'lst-ib')
search_box.send_keys('test123123')
search_box.send_keys(Keys.ENTER)  # Simple, reliable way to submit the search

# Wait for the resultStats element to load (max 10 seconds timeout)
result_stats = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, 'resultStats'))
)

# Grab and print the target text
print(result_stats.text)

# Clean up: close the browser properly
driver.quit()

Extra Tips for Better Reliability

  • If lst-ib stops working (Google occasionally updates element IDs), use the search box's name attribute instead—it's more stable:
    search_box = driver.find_element(By.NAME, 'q')
    
  • For even more robustness, add a wait for the search box too, in case the page takes time to fully load:
    search_box = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.NAME, 'q'))
    )
    

This code ensures we only interact with elements once they've fully loaded, which should eliminate the "element not found" errors you're probably hitting. Let me know if you run into any other hiccups!

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

火山引擎 最新活动