如何使用 selenium 在 python 中使不可点击的按钮可点击?

How to make nonclickable button click able in python using selenium?

嗨开始之前感谢您的提前帮助 所以我正在尝试抓取 google 航班网站:https://www.google.com/travel/flights

当抓取时,我已经完成了向文本字段发送键,但我一直点击搜索按钮,它总是给出错误,即该字段在某个点不可点击,或者其他元素会收到点击

错误图片是

代码是

from time import sleep
from selenium import webdriver
chromedriver_path = 'E:/chromedriver.exe'
def search(urrl):
 driver = webdriver.Chrome(executable_path=chromedriver_path)
 driver.get(urrl)
 asd= "//div[@aria-label='Enter your destination']//div//input[@aria-label='Where else?']"
 driver.find_element_by_xpath("/html/body/c-wiz[2]/div/div[2]/c-wiz/div/c-wiz/c-wiz/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[4]/div/div/div[1]/div/div/input").click()
 sleep(2)
 TextBox = driver.find_element_by_xpath(asd)
 sleep(2)
 TextBox.click()
 sleep(2)
 print(str(TextBox))
 TextBox.send_keys('Karachi')
 sleep(2)
 search_button = driver.find_element_by_xpath('//*[@id="yDmH0d"]/c-wiz[2]/div/div[2]/c-wiz/div/c-wiz/c-wiz/div[2]/div[1]/div[1]/div[2]/div/button/div[1]')
 sleep(2)
 search_button.click()
 print(str(search_button))
 sleep(15) 
 print("DONE")
 driver.close()
def main():
 url = "https://www.google.com/travel/flights"
 print(" Getitng Data ")
 search(url)
if __name__ == "__main__":
 main()

我是通过使用开发工具复制 Xpath 来完成的 再次感谢

而不是这个绝对 xapth

//*[@id="yDmH0d"]/c-wiz[2]/div/div[2]/c-wiz/div/c-wiz/c-wiz/div[2]/div[1]/div[1]/div[2]/div/button/div[1]

我建议你有一个相对路径:

//button[contains(.,'Search')]

此外,我建议您在尝试点击操作时明确等待。

代码:

search_button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(.,'Search')]")))
search_button.click()

您还需要以下导入:

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

专业提示:

以全屏模式启动浏览器。

driver.maximize_window()

你应该在 driver.get(urrl) 命令之前有上面的行。

您遇到的问题是,在文本框中输入城市 Karachi 后,Search 按钮上方会显示一个建议下拉菜单。这是异常的原因,因为下拉菜单将收到点击而不是搜索按钮。该网站的预期用途是 select 下拉列表中的城市,然后继续。

一个快速解决方法是首先查找源中的所有下拉菜单(有几个),然后使用 is_displayed() 查找当前处于活动状态的下拉菜单。接下来,您将 select 下拉列表中建议的第一个元素:


.....
TextBox.send_keys('Karachi')
sleep(2)

# the attribute(role) in the dropdowns element are named 'listbox'. Warning: This could change in the future
all_dropdowns = driver.find_elements_by_css_selector('ul[role="listbox"]')

# the active dropdown
active_dropdown = [i for i in all_dropdowns if i.is_displayed()][0]

# click the first suggestion in the dropdown (Note: this is very specific to your search. It could not be desirable in other circumstances and the logic can be modified accordingly)
active_dropdown.find_element_by_tag_name('li').click()

# I recommend using the advise @cruisepandey has offered above regarding usage of relative path instead of absolute xpath
search_button = driver.find_element_by_xpath("//button[contains(.,'Search')]")
sleep(2)
search_button.click()
.....

还建议领导@cruisepandey 提供的建议,包括研究更多关于 selenium 中显式等待的信息,以编写性能更好的 selenium 程序。祝一切顺利