![](/img/trans.png)
[英]How to click the button and get the source of new page with python-selenium?
[英]How to click a button with Selenium that don't exist at browser.page_source
我想點擊按鈕Alle akzeptieren 。 不幸的是,當我在 print(browser.page_source) 中搜索時,我沒有找到它。 WebDriverWait(browser, 10)
沒有幫助。
我的代碼:
browser = webdriver.Firefox(executable_path='./geckodriver')
browser.get("https://www.finanzen.net/")
browser.find_element_by_xpath("//button[@class_='message-component message-button no-children button-responsive-primary']").click()
來自因戈爾施塔特的問候
這是因為按鈕和“彈出窗口”本身位於iframe
內部:
在找到並單擊按鈕之前,您需要切換到它:
# switch to frame
frame = browser.find_element_by_css_selector("iframe[id^=sp_message_iframe]")
browser.switch_to.frame(frame)
# click the button
button = browser.find_element_by_css_selector("button.message-button.button-responsive-primary")
button.click()
# switch back to the default context
browser.switch_to.default_content()
請注意,您可能需要明確等待框架出現以允許頁面時間加載並在框架中顯示對話框:
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
browser = webdriver.Firefox(executable_path='./geckodriver')
browser.get("https://www.finanzen.net/")
wait = WebDriverWait(browser, 10)
# switch to frame
frame = wait.until(
EC.visibility_of_element_located((By.CSS_SELECTOR, "iframe[id^=sp_message_iframe]"))
)
browser.switch_to.frame(frame)
# click the button
button = browser.find_element_by_css_selector("button.message-button.button-responsive-primary")
button.click()
# switch back to the default context
browser.switch_to.default_content()
所需的元素Alle akzeptieren位於<iframe>
中,因此您必須:
誘導WebDriverWait使所需的幀可用並切換到它。
誘導WebDriverWait使所需元素成為可點擊的。
您可以使用以下任一定位器策略:
使用CSS_SELECTOR
:
driver.get("https://www.finanzen.net/") WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[id^='sp_message_iframe'][src^='https://consent.finanzen.net/index.html']"))) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[title='Alle akzeptieren']"))).click()
使用XPATH
:
driver.get("https://www.finanzen.net/") WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[starts-with(@id, 'sp_message_iframe') and starts-with(@src, 'https://consent.finanzen.net/index.html')]"))) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@title='Alle akzeptieren']"))).click()
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以在以下位置找到一些相關的討論:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.