如何使用Selenium和Python查找后代标签元素

问题描述 投票:0回答:1

我正在使用Selenium python尝试找出fisrt div下的所有后代,

所以我用了这段代码:

label_element =driver.find_elements_by_xpath("//div[@style='display:block']/descendant::label")

但是得到一个空列表[]。

<div id="coption5" class="copt" style="display: block;">
<div style="height:100%;display:flex;align-items:center;justify-content:center;">
<div class="coptw">
<div style="width:100%;height:49px;border-bottom:1px solid #888">
<b class="cpopdish">SUPREME CALZONE (M)  10.99</b>
<b class="cpopmodifi gray" data-iid="0" style="font-weight: normal;">
<i class="fa fa-comments-o"></i> Special Request</b><b class="cpopprice">10.99</b></div>
<div class="comain" style="right: 0px;">
<div class="crow" grp="0" grpname="">

<label class="label0" cid="5" style="">
<input type="radio" name="0" coname="BF PEPPERONI(M)" sname="" price="0.00" value="2">BF PEPPERONI(M)<b class="ip">0.00</b>
</label>
<label class="label0" cid="5"><input type="radio" name="0" coname="BLACK OLIVES(M)" sname="" price="0.00" value="3">BLACK OLIVES(M)<b class="ip">0.00</b>
</label>
<label class="label0" cid="5"><input type="radio" name="0" coname="CHICKEN(M)" sname="" price="1.00" value="4">CHICKEN(M)<b class="ip">1.00</b>
</label>
<div style="clear:both"></div></div>
</div><a class="ocancel" data-cid="5" data-grps="0"><i class="fa fa-remove"></i> Cancel</a></div></div>

任何朋友都知道如何使用Xpath或Css选择器来查找所有标签标记吗?

我的代码的第一部分:

driver.find_elements_by_xpath("//div[@style='display:block']

可以成功找到第一个div元素,所以我认为可见性问题可能没有问题。

the label tag is inside the first div tag,label are the descendant of the first div.

所以有什么朋友可以帮忙吗?

python selenium xpath css-selectors webdriverwait
1个回答
0
投票

这里是将找到所有3个标签的正确xpath。

//div[@style='display: block;']/descendant::label

enter image description here


0
投票

要使用<label>PythonSelenium中提取所有文本项,您必须为visibility_of_all_elements_located()引入WebDriverWait,并且可以使用以下Locator Strategies之一:] >

  • 使用CSS_SELECTOR

    print([my_elem.text for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.copt[id^='coption'] div.comain>div.crow>label")))])
    
  • 使用XPATH

print([my_elem.text for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='copt' and starts-with(@id, 'coption')]//div[@class='comain']/div[@class='crow']/label")))])
  • :您必须添加以下导入:
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    © www.soinside.com 2019 - 2024. All rights reserved.