[英]How to get all strings from all nested tags of a xml tag with python's lxml.etree library?
[英]How to extract text from lxml.etree tags based on value of sibling tags
我的目標是從xml文檔(鏈接)中提取URL並將其放在列表中: https : //www.valuespreadsheet.com/iedgar/results.php? stock=NFLX&output=xml
我從lxml
導入etree
並創建了一個列表etree
,該列表etree
從所有<instanceUrl>
標記中提取文本。
url = 'https://valuespreadsheet.com/iedgar/results.php?stock=NFLX&output=xml'
et = etree.fromstring(urlopen(url).read())
return [_.find('instanceUrl').text for _ in et.find('filings')]
現在,我想限制列表,以便僅從<instanceUrl>
標記中提取文本,其中<formType>
= 10K。
我該如何實現?
您需要一個XPath表達式和xpath()
方法 :
[url.text for url in et.xpath('//filing[formType = "10-K"]/instanceUrl')]
在這里,我們正在過濾包含帶有10-K
文本的formType
子節點的filing
節點,然后獲取instanceUrl
子節點。
請注意, _
變量名用於一次性變量 -必須定義但未實際使用的變量(例如,在解壓縮過程中)。 就您而言,您實際上已經使用過它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.