簡體   English   中英

如何使用Selenium Webdriver和Python來獲取子屬性?

[英]How to grab child attribute using Selenium Webdriver with Python?

我試圖抓住一個孩子的屬性。 我在Chrome中檢查我的元素,並查看以下代碼:

<div class="input-wrapper">
  <ion-label style="text-overflow: ellipsis; display; block; overflow: hidden;white-space: nowrap;" class="label label-md" id="lbl-80" producttypeid="39553">Item 1</ion-label>

我需要的屬性是“ producttypeid”。

當我右鍵單擊第一行並選擇其選擇器時,以下命令沒有任何作用: browser.find_element_by_css_selector("cssFromChrome").get_attribute("producttypeid")

當我右鍵單擊第二行並選擇它的選擇器時,我得到的選擇器是#lbl-80 ,這對我#lbl-80 ,因為它是動態的,我需要靜態的東西來抓取該元素。

我還能嘗試獲取該屬性嗎?

如果id總是唯一地以lbl-開頭,則選項之一是正則表達式匹配

browser.find_element_by_css_selector("ion-label[id^='lbl-']").get_attribute("producttypeid")

另一種選擇是使用孩子

browser.find_element_by_css_selector(".input-wrapper > ion-label").get_attribute("producttypeid")

按照HTML,如果要提取子項的producttypeid屬性,則可以編寫如下函數:

def get_producttypeid(myString):
        print(driver.find_elements_by_xpath("//div[@class='producttypeid']/ion-label[@class='label label-md' and starts-with(@id,'lbl-')][.='" + myString + "']").get_attribute("producttypeid"))

現在,您可以使用所需的商品說明(例如商品1 get_producttypeid()調用get_producttypeid()方法,以按如下方式檢索producttypeid屬性:

get_producttypeid("Item 1");

怎么樣:

element = browser.find_element_by_xpath("//*[contains(@id, 'lbl') and contains(text(), 'Item 1')]").get_attribute("producttypeid")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM