python - 在 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
解决方案
您可以使用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
推荐阅读
- html - Python BeautifulSoup - 试图在多个 div 中获取没有任何类的跨度值
- python - 蛇与 Python 和 Pygame
- c++ - 为什么我的 arduino 按钮在 0 和 1 以外的端口上不起作用?
- python-3.x - 处理窗口弹出硒
- flutter - 如何正确地将值传递给 Flutter 中任何小部件的事件处理函数?
- python - 如何匹配某个单词后的所有内容
- ssl - Nginx certbot:手动设置 pem 文件以在 https 上服务子域和主域
- google-sheets - 按 C 列排序,但将 F 列中的值分组
- javascript - 如何根据其他数组的值过滤对象数组?
- asp.net - asp.net mvc 发布了如何将文件保存在 iss 服务器中以及如何找到此文件夹路径