【问题标题】:Python and Selenium - Select specific radio button based on name and text withinPython 和 Selenium - 根据名称和文本选择特定的单选按钮
【发布时间】:2020-04-15 23:50:30
【问题描述】:

我正在尝试使用 python 和 selenium 从网页中的几个单选按钮中选择一个特定的单选按钮。幸运的是,我要选择的单选按钮确实关联了特定的文本,这应该让我更容易选择。不幸的是,我错过了一些东西,因为所有尝试都出错了。下面是 HTML 代码,我尝试过的,以及我想要实现的。

HTML

    <div data-a-input-name="slotsRadioGroup" class="a-radio a-radio-fancy slotButtonRadio"><label><input type="radio" name="slotsRadioGroup" value="" autocomplete="off"><i class="a-icon a-icon-radio"></i><span class="a-label a-radio-label">
        <span class="slotRadioLabel">
            5PM - 7PM
        </span>

    <div class="a-row">
        <span class="a-size-small slot-button-micro-copy preselected-visible">
            Soonest available time with all items.
        </span>
    </div>


    </span></label></div>

</div></div>

我需要选择的单选按钮将始终显示文本“Soonest available...”。

我的尝试

我尝试了不同的 xpath 代码变体来尝试根据文本选择它。我的最后一次尝试是:

driver.find_element_by_xpath("//input[@type='radio']and following-sibling::span[contains(., 'Soonest available')").click()

这会导致以下错误:

SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//input[@type='radio']and following-sibling::span[contains(., 'Soonest available')' is not a valid XPath expression.

预期结果 我想要的是能够根据上面存在的文本选择特定的单选按钮。

【问题讨论】:

标签: python python-3.x selenium xpath selenium-chromedriver


【解决方案1】:

根据文本选择单选按钮 Induce WebDriverWait 并等待 element_to_be_clickable() 并遵循 xpath 选项。

XPATH 1:

WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//label[.//span[contains(.,'Soonest available time with all items')]]/input[@name='slotsRadioGroup']"))).click()

XPATH 2:

WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//span[contains(.,'Soonest available time with all items')]/preceding-sibling::input[1]"))).click()

如果Web驱动点击不起作用,那么你可以尝试javascripts执行器点击同样的。

radiobtn=WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,"//label[.//span[contains(.,'Soonest available time with all items')]]/input[@name='slotsRadioGroup']")))

driver.execute_script("arguments[0].click();", radiobtn)

注意:- 您需要导入以下库。

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

【讨论】:

    【解决方案2】:

    试试这个:

    for i in driver.find_elements_by_tag_name("span"):
        if "Soonest available" in i.text:
            result = i
            break
    

    【讨论】:

      猜你喜欢
      • 2016-05-18
      • 1970-01-01
      • 2017-04-22
      • 2015-07-22
      • 1970-01-01
      • 2021-02-18
      • 2017-12-03
      • 2011-10-01
      • 1970-01-01
      相关资源
      最近更新 更多