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
resultStatsright after sending keys, the element won't exist yet, causing aNoSuchElementException. - Your
ActionChainscode was cut off, and submitting the search can be done more reliably with a simpleENTERkey 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-ibstops 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




