如何使用 Selenium 和 Python 单击搜索按钮?

How to click on the Search button using Selenium and Python?

The screenshot of inspect code of this web page。我只想动态点击按钮 "search" 但我尝试了很多方法,但总是有问题..网络抓取新手

我试过:

from selenium import webdriver

my_url = 'https://sbs.naic.org/solar-external-lookup/lookup?jurisdiction=AL&searchType=Company&companyStatus=AC'

driver = webdriver.Chrome('D:/chromedriver')

driver.get(my_url)
driver.find_element_by_css_selector(".btn.btn-primary").click()
driver.find_element_by_xpath("//div[@class='btn btn-primary' and @id='submitBtn']").click()
driver.find_element_by_css_selector(".btn.btn-primary").click()

只希望我的页面可以点击"search"按钮进入下一页

要处理动态元素,请使用 WebDriverWait,然后单击该元素。

WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH,'//button[@class="btn btn-primary" and @id="submitBtn"]'))).click()

请使用以下导入来执行上面的代码。

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

如果有帮助请告诉我。

无法访问 website. However the element with text as Search seems to be Angular element so to click() on the element you have to induce WebDriverWait for the element to be clickable and you can use either of the following :

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.btn-group[aria-label='Search']>button.btn.btn-primary#submitBtn"))).click()
    
  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='btn-group' and @aria-label='Search']/button[@class='btn btn-primary' and @id='submitBtn']"))).click()
    
  • 注意:您必须添加以下导入:

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

有时 .click() 不起作用,我不确定为什么。当发生这种情况时,请尝试 .send_keys(Keys.ENTER)

我使用的是 Firefox,并在下面的代码中注释掉了我的 geckodriver 可执行路径。我还通过 id 而不是 css 选择器定位元素。

from selenium import webdriver

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains


my_url = 'https://sbs.naic.org/solar-external-lookup/lookup?jurisdiction=AL&searchType=Company&companyStatus=AC'

driver = webdriver.Chrome('D:/chromedriver')
# driver = webdriver.Firefox(executable_path=r'C:\Py\geckodriver.exe');

driver.get(my_url)

click_search = driver.find_element_by_id("submitBtn")
click_search.send_keys(Keys.ENTER)