【问题标题】:Clicking a button in JavaScript page - Selenium/Python单击 JavaScript 页面中的按钮 - Selenium/Python
【发布时间】:2021-03-11 22:56:25
【问题描述】:

我的代码访问了一个页面,我试图单击菜单列表上显示“医师计划”的按钮。如果您在浏览器上单击此按钮,它会将您定向到一个新网页。

但是,页面的 html 上没有 href 可以帮助我通过代码找到此链接(我假设是因为它是 JavaScript?)目前,我只使用了它的 Xpath。

我的问题是 - 如果我能够在浏览器中点击它,我不应该能够使用 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()

【问题讨论】:

  • 如果使用xpath可以成功定位到按钮,那么问题出在哪里?
  • 还有为什么它是一个webelement而不是android或mobilelement

标签: javascript python selenium click


【解决方案1】:

元素在 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

【讨论】:

  • 谢谢,什么是 iFrame,您是如何在 HTML 的检查部分找到“SCM20 高级从业者计划”的?我可以在这里找到其他选项吗?
【解决方案2】:
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()

【讨论】:

  • 谢谢,什么是 iFrame,您是如何在 HTML 的检查部分找到“SCM20 高级从业者计划”的?我可以在这里找到其他选项吗?
  • 即标签名为 iframe 的元素的 name 属性,iframe 在您的网页内创建一个 ln 隔离框架
  • 我在网页上右击并点击检查,但我找不到您找到的内容?我希望能够对其他选项(药剂师计划等)执行此操作
  • 只需使用 options[2].click 等来选择相应的选项
  • 往回滚动看到pharmacist program的父级,可以看到有一个元素叫iframe作为父级
猜你喜欢
  • 2019-03-17
  • 1970-01-01
  • 2017-05-28
  • 1970-01-01
  • 2021-08-27
  • 2021-03-18
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
相关资源
最近更新 更多