首页 > 解决方案 > 在 Selenium,Python 中查找下一个兄弟元素?

问题描述

我需要先前选择的元素的兄弟姐妹。

例如:

<div class="dt">Technology</div>
<div class="da">GSM / CDMA / HSPA / EVDO / LTE</div>
<div class="dt">Dimensions</div>
<div class="da">149.9 x 70.4 x 7.8 mm (5.90 x 2.77 x 0.31 in)</div>
<div class="dt">Weight</div>
<div class="da">157 g (5.54 oz)</div>
<div class="dt">Build</div>
<div class="da">Back glass (Gorilla Glass 5), aluminum frame    </div>
<div class="dt">Type</div>
<div class="da">Dynamic AMOLED capacitive touchscreen, 16M colors</div>
<div class="dt">SIM</div>
<div class="da">Single SIM (Nano-SIM) or Hybrid Dual SIM)</div>

假设我需要“尺寸”和类型。

代码:

dts = browser.find_elements_by_class_name("dt");
for dt in dts :

    if dt.("innerText") == "Dimensions":
        print(dt.("innerText") + "-" + dt.**FollowingSibling**())
    if dt.("innerText") == "Type":
        print(dt.("innerText") + "-" + dt.**FollowingSibling**())

预期输出:

Dimensions - 149.9 x 70.4 x 7.8 mm (5.90 x 2.77 x 0.31 in)
Type - Dynamic AMOLED capacitive touchscreen, 16M colors

标签: pythonselenium

解决方案


您可以使用text属性或innerText随心所欲。试试下面的代码。

for dt in dts :

    if dt.text == "Dimensions":
        print(dt.text + "-" + dt.find_element_by_xpath("./following-sibling::div").text)
    if dt.text == "Type":
        print(dt.text + "-" + dt.find_element_by_xpath("./following-sibling::div").text)

或者

dts = browser.find_elements_by_class_name("dt");
for dt in dts :

    if dt.get_attribute("innerText")== "Dimensions":
        print(dt.get_attribute("innerText") + "-" + dt.find_element_by_xpath("./following-sibling::div").text)
    if dt.get_attribute("innerText") == "Type":
        print(dt.get_attribute("innerText") + "-" + dt.find_element_by_xpath("./following-sibling::div").text)

输出 :

Dimensions-149.9 x 70.4 x 7.8 mm (5.90 x 2.77 x 0.31 in)
Type-Dynamic AMOLED capacitive touchscreen, 16M colors

推荐阅读