【问题标题】:Loop the button selection循环按钮选择
【发布时间】:2018-06-25 02:41:44
【问题描述】:

我正在尝试自动化选择过程。在下面的示例中,我尝试按 ID 选择按钮。我不想编写多行代码,而是想循环选择。

我的脚本是:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re

class NewTest(unittest.TestCase):
def setUp(self):
    self.driver = webdriver.Firefox()
    self.driver.implicitly_wait(30)
    self.base_url = "https://developer.mozilla.org/"
    self.verificationErrors = []
    self.accept_next_alert = True

def test_new(self):
    driver = self.driver
    driver.get(self.base_url + "/en-US/docs/Web/HTML/Element/input/radio")
    driver.find_element_by_id("contactChoice1").click()
    driver.find_element_by_id("contactChoice2").click()
    driver.find_element_by_id("contactChoice3").click()

def is_element_present(self, how, what):
    try: self.driver.find_element(by=how, value=what)
    except NoSuchElementException as e: return False
    return True

def is_alert_present(self):
    try: self.driver.switch_to_alert()
    except NoAlertPresentException as e: return False
    return True

def close_alert_and_get_its_text(self):
    try:
        alert = self.driver.switch_to_alert()
        alert_text = alert.text
        if self.accept_next_alert:
            alert.accept()
        else:
            alert.dismiss()
        return alert_text
    finally: self.accept_next_alert = True

HTML 是: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio

谁能帮我做这个

谢谢

【问题讨论】:

  • 请阅读How to Ask,尤其是关于minimal reproducible example(MCVE)和How much research effort is expected?的部分,这将帮助您调试自己的程序并自己解决问题。如果您这样做并且仍然卡住,您可以返回并发布您的 MCVE、您尝试过的内容以及执行结果(包括任何错误消息),以便我们更好地帮助您。还提供指向页面和/或相关 HTML 的链接。

标签: python loops selenium button getelementbyid


【解决方案1】:

您可以使用 type="radio" 创建所有元素的列表:

find_elements_by_xpath 

然后对于列表中的每个webelement,你可以做一个

element.click();

类似:

ids = driver.find_elements_by_xpath('//input[@type="radio"]')
for ii in ids:
ii.click();

【讨论】:

  • 我分享的 HTML 是示例。我有类似但按钮。可以通过 ID 实现
  • 是的,你可以使用(在这个例子中): //*[contains(@id, 'contactChoice')]
  • ids = driver.find_elements_by_id('//input[@type="radio"]') for ii in ids ii.click();像这样?
  • 不,问题在于,id 寻找绝对 id。因此,除非所有元素都具有相同的 id,否则它将是 xpath 或 css 选择器。
  • 确切地说我喜欢这个 driver.find_element_by_id("Product").click() driver.find_element_by_id("id1").click() driver.find_element_by_id("id1").click( ) driver.find_element_by_id("id2").click() driver.find_element_by_id("id2").click() driver.find_element_by_id("id3").click() driver.find_element_by_id("id3").click() driver .find_element_by_id("id4").click() driver.find_element_by_id("id4").click()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 2016-09-28
相关资源
最近更新 更多