簡體   English   中英

單擊 JavaScript 頁面中的按鈕 - Selenium/Python

[英]Clicking a button in JavaScript page - Selenium/Python

我的代碼訪問一個頁面,我試圖單擊菜單列表上顯示“醫師程序”的按鈕。 如果您在瀏覽器上單擊它,它會將您定向到一個新網頁。

但是,頁面的 html 上沒有可以幫助我通過代碼找到此鏈接的 href(我假設是因為它是 JavaScript?)目前,我只使用了它的 ZD22CFAC75B2DA745E95E22E9F2BC956

我的問題是 - 如果我能夠在瀏覽器中單擊它,我不應該能夠使用 Selenium 來單擊它嗎? 如果是這樣,如何做到這一點?

import time
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome()

driver.get('https://www.kidney.org/spring-clinical/program')
time.sleep(6)
page_source = driver.page_source
soup = BeautifulSoup(page_source, 'html.parser')
element1 = driver.find_element_by_xpath('//*[@id="dx-c7ad8807-6124-b55e-d292-29a4389dee8e"]/div')
element1.click()

該元素在 iframe 內,您需要切換到 iframe

driver.switch_to.frame("SCM20 Advanced Practitioner Program")
element1 = driver.find_element_by_xpath("//div[text()='Physician Program']")
element1.click()

理想情況下,您應該使用webdriverwait並等待框架可用。

WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,"SCM20 Advanced Practitioner Program"))) 
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH "//div[text()='Physician Program']"))).click()

您需要導入以下庫

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

import subprocess
#other imports
import time
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome()

driver.get('https://www.kidney.org/spring-clinical/program')
time.sleep(6)
page_source = driver.page_source
soup = BeautifulSoup(page_source, 'html.parser')
frame= WebDriverWait(driver,10).until(EC.presence_of_element_located(
    (By.NAME, "SCM20 Advanced Practitioner Program")))
driver.switch_to.frame(frame)
options = WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located(
    (By.CSS_SELECTOR, '[class="track-selector-popup"] [role="option"]')))

options[0].click()

input()

元素在 iframe 內部,因此切換到它並使用等待,切換回並與框架外的元素交互使用:

  driver.switch_to.default_content()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM