【问题标题】:change a parent class based on children information根据子信息更改父类
【发布时间】:2021-09-09 07:57:32
【问题描述】:

我刚开始使用 selenium,就来到了这个网站:https://equi.generali.fr/devis-en-ligne-proprietaire-d-un-equide

有这些按钮:

包含以下元素:

我遇到的问题是这两个按钮的 id 名称相同。据我所知,我不能只使用 selenium 的 click 功能。我必须从“btn”更改为“btn active”才能激活按钮。

因此,有了这些信息,我如何根据子信息将 div class="btn" 更改为 div class="btn active"。或者有没有更简单的方法我没有看到?

到目前为止我的代码:

btn_cookie = driver.find_element_by_id('popin_tc_privacy_button')
btn_cookie.click()

input_year = driver.find_element_by_id('quote_equine_owner_equineBirthYear')

input_gear = driver.find_element_by_id('quote_equine_owner_equineValue')

input_rcpe_yes = driver.find_element_by_id('quote_equine_owner_hasSubscribedRcpe_0')
input_rcpe_no = driver.find_element_by_id('quote_equine_owner_hasSubscribedRcpe_1')

input_sub_yes = driver.find_element_by_id('quote_equine_owner_subscribeVeterinaryCharge_0')
input_sub_no = driver.find_element_by_id('quote_equine_owner_subscribeVeterinaryCharge_1')

options_year = []
for option in input_year.find_elements_by_tag_name('option'):
    options_year.append(option.get_attribute("value"))

options_gear = []
for option in input_gear.find_elements_by_tag_name('option'):
    options_gear.append(option.get_attribute("value"))

yes_no = ['yes','no']
containers = driver.find_elements_by_xpath('//div[@class="btn-group  btn-group-toggle row mx-auto align-items-center justify-content-center"]')
print(containers)

for item in containers:
    print(item)

for year in options_year:
    input_year.send_keys(year)
    time.sleep(2)
    if int(year) > 2000:
        for price in options_gear:
            input_gear.send_keys(price)
            time.sleep(2)

我正在尝试遍历这些信息以获取最后的价格并存储它们。

谢谢。

【问题讨论】:

  • 我看不出他们有相同的id,你能指出id重复的地方吗?谢谢。

标签: python css selenium


【解决方案1】:

找到解决办法:

按钮中唯一不同的 id 是在子分支中,所以:

#find child element
input_rcpe_yes = driver.find_element_by_id('quote_equine_owner_hasSubscribedRcpe_0')
input_rcpe_no = driver.find_element_by_id('quote_equine_owner_hasSubscribedRcpe_1')
#go up two steps to parent element
btn_yes_1 = input_rcpe_yes.find_element_by_xpath('./../..')
btn_no_1 = input_rcpe_no.find_element_by_xpath('./../..')
#change parent element to active or non active
driver.execute_script("arguments[0].setAttribute('class', 'btn')", btn_yes_1)
driver.execute_script("arguments[0].setAttribute('class', 'btn active')", btn_no_1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2021-12-09
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多