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

问题描述:

我正在使用Selenium python尝试找出第一个div下的所有后代,所以我使用了以下代码:

I'm using Selenium python to try to find out all the descendant under the first div, so I used this code:

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

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

But get an empty list [].

<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选择器来查找所有标签标记吗?

Any friend know how to use Xpath or Css selector to locate all the label tag?

我的代码的第一部分:

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

可以成功找到第一个div元素,因此我认为可见性问题可能没有问题. label标签位于第一个div标签内,label是第一个div的后代.

Can locate the first div element successfully so I think maybe there is nothing wrong with the visibility issues. The label tag is inside the first div tag, label are the descendant of the first div.

那么任何朋友都可以帮忙吗?

So any friend can help?

使用定位器策略:

To extract all the text items from the <label> using Selenium and Python you have to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following 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")))])
    

  • 注意:您必须添加以下导入:

  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC