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

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

使用 BeautifulSoup 遍歷 XML 并拉取下一個兄弟

使用 BeautifulSoup 遍歷 XML 并拉取下一個兄弟

慕虎7371278 2022-10-18 16:29:04
我已將 PDF 轉換為 XML 以便于解析。我的 XML 示例如下:<LTTextLineHorizontal bbox="[58.501, 729.764, 78.501, 737.764]" height="8.0" width="20.0" word_margin="0.1" x0="58.501" x1="78.501" y0="729.764" y1="737.764"><LTTextBoxHorizontal bbox="[58.501, 729.764, 78.501, 737.764]" height="8.0" index="13" width="20.0" x0="58.501" x1="78.501" y0="729.764" y1="737.764">Date: </LTTextBoxHorizontal></LTTextLineHorizontal><LTTextLineHorizontal bbox="[107.249, 730.004, 147.281, 738.004]" height="8.0" width="40.032" word_margin="0.1" x0="107.249" x1="147.281" y0="730.004" y1="738.004"><LTTextBoxHorizontal bbox="[107.249, 730.004, 147.281, 738.004]" height="8.0" index="14" width="40.032" x0="107.249" x1="147.281" y0="730.004" y1="738.004">02/26/2020 </LTTextBoxHorizontal></LTTextLineHorizontal>“日期:”在一行上,下一個兄弟(我認為這就是它的名字)的值是“02/26/2020”。我試過了:from bs4 import BeautifulSoupxml = open("test3.xml").read()soup = BeautifulSoup(xml)print(soup.find(text="Date:").findNext('LTTextLineHorizontal').contents[0])我得到錯誤:AttributeError: 'NoneType' object has no attribute 'findNext'我的目標是遍歷 XML 并提取所需的變量(即日期)并將它們放入數據框中。但我什至還沒有走到那一步。輸出可能是字典或日期字符串:02/26/2020
查看完整描述

1 回答

?
慕娘9325324

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

使用正則表達式re。


import re

from bs4 import BeautifulSoup

xml = open("test3.xml").read()

soup = BeautifulSoup(xml,'lxml')

print(soup.find('lttextboxhorizontal',text=re.compile("Date:")).find_next('lttextboxhorizontal').text)

或者


import re

from bs4 import BeautifulSoup

xml = open("test3.xml").read()

soup = BeautifulSoup(xml,'lxml')

print(soup.find(text=re.compile("Date:")).find_next('lttextboxhorizontal').text)

您可以在沒有正則表達式的情況下執行此操作,也可以放置一個空格。


from bs4 import BeautifulSoup

xml = open("test3.xml").read()

soup = BeautifulSoup(xml,'lxml')

print(soup.find(text="Date: ").find_next('lttextboxhorizontal').text)


查看完整回答
反對 回復 2022-10-18
  • 1 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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