亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python中通過絕對值獲取XML文件中的值

Python中通過絕對值獲取XML文件中的值

慕桂英3389331 2023-10-25 10:49:16
我有一個我想要檢索的 XML 文件值的絕對路徑。絕對路徑的格式為“A/B/C”。我怎樣才能在Python中做到這一點?
查看完整描述

3 回答

?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

使用ElementTree庫(請注意,我的答案使用核心 python 庫,而其他答案使用外部庫。)


要抓取前三個句子,只需將這些行添加到您的代碼中:


section = soup.find('section',class_ = "article_text post") #Finds the section tag with class "article_text post"


txt = section.p.text #Gets the text within the first p tag within the variable section (the section tag)


print(txt)

輸出:


Many people will land on this page after learning that their email address has appeared in a data breach I've called "Collection #1". Most of them won't have a tech background or be familiar with the concept of credential stuffing so I'm going to write this post for the masses and link out to more detailed material for those who want to go deeper.

希望這有幫助!


查看完整回答
反對 回復 2023-10-25
?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

另一種方法。


from simplified_scrapy import SimplifiedDoc, utils, req


# Basic

xml = '''<ROOT><A><B><C>The Value</C></B></A></ROOT>'''

doc = SimplifiedDoc(xml)

print (doc.select('A>B>C'))


# Multiple

xml = '''<ROOT><A><B><C>The Value 1</C></B></A><A><B><C>The Value 2</C></B></A></ROOT>'''

doc = SimplifiedDoc(xml)

# print (doc.selects('A').select('B').select('C'))

print (doc.selects('A').select('B>C'))


# Mixed structure

xml = '''<ROOT><A><other>no B</other></A><A><other></other><B>no C</B></A><A><B><C>The Value</C></B></A></ROOT>'''

doc = SimplifiedDoc(xml)

nodes = doc.selects('A').selects('B').select('C')

for node in nodes:

  for c in node:

    if c:

      print (c)

結果:


{'tag': 'C', 'html': 'The Value'}

[{'tag': 'C', 'html': 'The Value 1'}, {'tag': 'C', 'html': 'The Value 2'}]

{'tag': 'C', 'html': 'The Value'}


查看完整回答
反對 回復 2023-10-25
?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

您可以使用lxml,您可以通過安裝pip install lxml。


from simplified_scrapy import SimplifiedDoc, utils, req


# Basic

xml = '''<ROOT><A><B><C>The Value</C></B></A></ROOT>'''

doc = SimplifiedDoc(xml)

print (doc.select('A>B>C'))


# Multiple

xml = '''<ROOT><A><B><C>The Value 1</C></B></A><A><B><C>The Value 2</C></B></A></ROOT>'''

doc = SimplifiedDoc(xml)

# print (doc.selects('A').select('B').select('C'))

print (doc.selects('A').select('B>C'))


# Mixed structure

xml = '''<ROOT><A><other>no B</other></A><A><other></other><B>no C</B></A><A><B><C>The Value</C></B></A></ROOT>'''

doc = SimplifiedDoc(xml)

nodes = doc.selects('A').selects('B').select('C')

for node in nodes:

? for c in node:

? ? if c:

? ? ? print (c)

結果:


{'tag': 'C', 'html': 'The Value'}

[{'tag': 'C', 'html': 'The Value 1'}, {'tag': 'C', 'html': 'The Value 2'}]

{'tag': 'C', 'html': 'The Value'}


查看完整回答
反對 回復 2023-10-25
  • 3 回答
  • 0 關注
  • 207 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號