Selenium Python在不同的条件下将Textvar链接到子级中的Valuevar

2024-10-04 11:29:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

<div class="_97KWR">
<div class="_12x3s">
  <div class="_1PF0y">
     <div class="_1xNd0 CTwrR _3ASIK">
        <a class="_3bf_k _1WIu4" href="/en/gilgamesh/hola-dola/gof-turkey-championship-2019-555/live/gazorpazorp/log-arena-fams-5551565"><span>Franco Pescatore</span></a>
        <div class="_2cZpo">
           <svg width="32px" height="32px" xmlns="http://www.w3.org/2000/svg">
              <use xlink:href="dist/icons.svg#hula-hula"></use>
           </svg>
        </div>
        <div class="_1sT8o _2ALVH">
           <div class="_2Li3l _1fAz9"><img src="/dist/disabled-gg.png" alt="Disabled gg"></div>
        </div>
     </div>
     <div class="_2b9x1">
        <div>
           <svg width="18px" height="14px" xmlns="http://www.w3.org/2000/svg">
              <use xlink:href="dist/icons.svg#vs"></use>
           </svg>
        </div>
     </div>
     <div class="_1xNd0 CTwrR _3ASIK">
        <a class="_3bf_k _1WIu4" href="/en/gilgamesh/hola-dola/gof-turkey-championship-2019-555/live/gazorpazorp/log-arena-fams-5551565"><span>Giorgio Pescato</span></a><img class="_25rWl _2cZpo" alt="Giorgio Pescato" src="https://ultramedia.com/Media/GiorgioPescato_f6f84978-6da4-4e14-a36b-860dce530d08.png">
        <div class="_1sT8o _2ALVH">
           <div class="_2Li3l _1fAz9"><img src="/dist/disabled-gg.png" alt="Disabled gg"></div>
        </div>
     </div>
  </div>
 <div class="_1xNd0 CTwrR">
    <a class="_3bf_k _1WIu4" href="'/en/gilgamesh/hola-dola/swing/fun#4844844"> 
 <span>BipolarFun</span></a><img class="_25rWl _2cZpo" alt="BipolarFun" src="https://promedia.com/Media//en/gilgamesh/hola-dola/swing/4844844.png">
 <div class="_1sT8o _2ALVH">
   <button class="_2Li3l _1fAz9"><span>1,30</span></button>
  <div class="_1CeGR">
     <div class="_1T5lR"></div>
    </div>
   </div>
 </div>

它是这样动态变化的, 因为DIV的类是动态的,所以我通过使用xpath

//a[starts-with(@href,'/en/gilgamesh/hola-dola/

有了这个,我可以像弗朗哥·佩斯卡托雷或乔治·佩斯卡托那样称呼他 使用xpath

//button[starts-with(@class,'_')]

我可以访问值,但不能在“禁用”时访问

我也不能先做第一个,然后再做其他的,因为它返回的元素数量不一样,所以我在链接Text元素和Value元素时遇到了问题,Value元素在一个子元素中

最后,资源应该是这样的:

n[0] = 'BipolarFun'
a[0] = 1,30
n[1] = 'Franco Pescatore'
a[1] = 0 #disabled
n[2] = 'Giorgio Pescato'
a[2] = 0 #disabled

请帮帮我,我卡住了


Tags: svgdivsrc元素imgusedistclass
1条回答
网友
1楼 · 发布于 2024-10-04 11:29:34

您可以尝试的代码:

# get all labels
labels = driver.find_elements_by_xpath("//a[contains(@href,'/en/gilgamesh/hola-dola/')]")
for label in labels:
    # get buttons inside label's parent DIV
    buttons = label.find_elements_by_xpath("./ancestor::div[1]//button")
    # if buttons more than 0, then get button text else use 0.
    button_value = buttons[0].text if len(buttons) > 0 else 0
    print(f"Label: {label.text}, value: {button_value}")

相关问题 更多 >