首页 > 解决方案 > 使用 Selenium(Python)单击按钮无效

问题描述

我正在尝试从NSE 站点获取 Block Deals 数据。我已经自动化了选择
1) 从下拉菜单中选择大宗交易的过程。
2)点击单选按钮和发送日期(从和到)。
但是当我尝试单击“获取数据”按钮时,什么也没有发生。即使可以定位按钮元素并且输出显示按钮已被单击,但似乎根本没有任何效果。
在此处输入图像描述

图像中标记的元素:-

<p>
<img onclick="document.getElementById('submitMe').click()" id="get" src="/common/images/btn-get-data.gif" style="margin-left: 20px;" class="getdata-button">  
<input type="button" style="display:none" onclick="submitData();" id="submitMe" tabindex="9" value="Get Results">
</p>

我尝试了很多方法,例如:
上述元素的 X_path:“/html/body/div 2 /div[3]/div 2 /div 1 /div[4]/div 1 /div/form/div 2 /div[ 3]/p/img"

1) driver.find_element_by_xpath("/html/body/div[2]/div[3]/div[2]/div[1]/div[4]/div[1]/div/form/div[2]/div[3]/p/img").click()
2) # Clicking with ActionChains
button = driver.find_element_by_xpath("/html/body/div[2]/div[3]/div[2]/div[1]/div[4]/div[1]/div/form/div[2]/div[3]/p/img")
ActionChains(driver).move_to_element(button).click(button).perform()
3) driver.execute_script("javascript:'get'")
4) driver.execute_script("document.getElementById('get').click()")
5) button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH,"/html/body/div[2]/div[3]/div[2]/div[1]/div[4]/div[1]/div/form/div[2]/div[3]/p/img")))  
button .click()

但是以上似乎都没有点击按钮并获取页面上的数据。
我的代码:-

# Select Block Deal from drop down
driver.find_element_by_xpath("//*[@id='dataType']/option[2]").click()

# Radio Button
if driver.find_element_by_id("rdDateToDate").get_attribute("type") == "radio":
    print("Element is a Radio button")
else:
    print("Element is not a Radio button")

radioElement = driver.find_element_by_id("rdDateToDate")
radioElement.click()

# From Date
from_date = driver.find_element_by_css_selector("#fromDate")
from_date.clear()
time.sleep(2)
month = "01"
year = "2019"
day = "01"
from_date.send_keys("{day}-{month}-{year}".format(day = day, month = month, year = year))

#To Date
to_date = driver.find_element_by_css_selector("#toDate")
to_date.clear()
time.sleep(2)
month = "12"
year = "2019"
day = "31"
to_date.send_keys("{day}-{month}-{year}".format(day = day, month = month, year = year))

# Clicking at random at Y = 300
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(to_date, 200,0)
action.click()
action.perform()

## Clicking at Get Data Button
????????

标签: pythonseleniumselenium-webdriver

解决方案


你有没有尝试发送密钥...

EC.element_to_be_clickable((By.XPATH,"/html/body/div[2]/div[3]/div[2]/div[1]/div[4]/div[1]/div/form/div[2]/div[3]/p/img")))  
button .send_keys(Keys.ENTER)

单选按钮的某些情况,您可能需要使用带有发送空间的动作链

xpath = '/html/body/div[2]/div[3]/div[2]/div[1]/div[4]/div[1]/div/form/div[2]/div[3]/p/img'
your_element = driver.find_element_by_xpath(xpath)
ActionChains(driver).move_to_element(your_element).send_keys(Keys.SPACE).perform()

推荐阅读