Python+Selenium点击提交按钮失败,求解决方案(附源码)
Fixing the Web Crawler Click Issue with Selenium
What's Wrong with Your Current Code?
- You’re trying to target a
<div>element with//div[@class="btn btn-primary"], but the actual clickable element is the<button>tag that carries thebtn btn-primaryclass. The div is just a container—it doesn’t have theonclickhandler that triggers the form submission. - The
aria-hidden="true"attribute on the inner<span>has nothing to do with your problem. That’s an accessibility attribute (it hides the icon from screen readers) and doesn’t block Selenium from interacting with the button.
Correct Ways to Locate and Click the Button
Here are several reliable methods to target the submit button:
1. CSS Selector (Target Button by Class)
Use a CSS selector to directly pick the button element with the correct classes:
driver.find_element(By.CSS_SELECTOR, "button.btn.btn-primary").click()
2. XPath (Target by Onclick Attribute)
Since the button has a unique onclick attribute, you can use that for precise targeting:
driver.find_element(By.XPATH, "//button[@onclick='javascript:document.forms[0].submit();']").click()
3. XPath (Target by Button Text)
If the "Search" text stays consistent, you can locate the button by its visible text:
driver.find_element(By.XPATH, "//button[contains(normalize-space(text()), 'Search')]").click()
Improved Full Code with Explicit Wait
For better reliability (especially with dynamic pages), replace implicit wait with an explicit wait to ensure the button is fully ready to be clicked:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # PhantomJS is deprecated—use Chrome for better compatibility driver = webdriver.Chrome(executable_path='C:/Users/50178/Documents/learn/pracpy/ChromeDriver/chromedriver.exe') driver.get("http://www16.co.hennepin.mn.us/cfrs/search.do") # Wait for the radio button to be clickable, then select it WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='radio']")) ).click() # Wait for the submit button to be clickable, then click it WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-primary")) ).click() # Add your post-click logic here (e.g., scrape the loaded page) # print(driver.page_source) driver.close()
Quick Notes
- Ditch PhantomJS: It’s no longer maintained—use Chrome/Firefox in headless mode instead for better compatibility with modern websites.
- Explicit Waits Are Better: They wait for a specific condition (like an element being clickable) instead of a fixed time, making your code more robust against slow-loading pages.
内容的提问来源于stack exchange,提问作者ChakaSan
相关产品推荐
相关产品推荐

