我正在嘗試獲取標簽之間的文本以及標簽集之間的文本,我已經嘗試過,但我沒有得到我想要的。任何人都可以幫忙嗎?對此,我真的非常感激。
text = '''
<b>Doc Type: </b>AABB
<br />
<b>Doc No: </b>BBBBF
<br />
<b>System No: </b>aaa bbb
<br />
<b>VCode: </b>040000033
<br />
<b>G Code: </b>000045
<br />
'''
預期輸出:
Doc Type: AABB
Doc No: BBBBF
System No: aaa bbb
VCode: 040000033
G Code: 000045
我嘗試過的代碼,這只給了我標簽之間的文本,而不是標簽外的文本:
soup = BeautifulSoup(html, "html.parser")
print(soup.find_all('b'))
我也嘗試了以下操作,但它給了我頁面上的所有文本,我只想要標簽之外的標簽和文本,:
soup = BeautifulSoup(html, "html.parser")
lines = ''.join(soup.text)
print(lines)
當前輸出為:
Doc Type:
Doc No:
System No:
VCode:
G Code:
uj5u.com熱心網友回復:
您可以使用.next_sibling這些元素中的每一個。
代碼:
html = '''
<b>Doc Type: </b>AABB
<br />
<b>Doc No: </b>BBBBF
<br />
<b>System No: </b>aaa bbb
<br />
<b>VCode: </b>040000033
<br />
<b>G Code: </b>000045
<br />'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
bs = soup.find_all('b')
for each in bs:
eachFollowingText = each.next_sibling.strip()
print(f'{each.text} {eachFollowingText}')
輸出:
Doc Type: AABB
Doc No: BBBBF
System No: aaa bbb
VCode: 040000033
G Code: 000045
uj5u.com熱心網友回復:
嘗試這個:
from bs4 import BeautifulSoup
text = '''
<b>Doc Type: </b>AABB
<br />
<b>Doc No: </b>BBBBF
<br />
<b>System No: </b>aaa bbb
<br />
<b>VCode: </b>040000033
<br />
<b>G Code: </b>000045
<br />
'''
result = [
i.getText(strip=True) for i in
BeautifulSoup(text, "html.parser").find_all(text=True)
if i.getText(strip=True)
]
print("\n".join([" ".join(result[i:i 2]) for i in range(0, len(result), 2)]))
輸出:
Doc Type: AABB
Doc No: BBBBF
System No: aaa bbb
VCode: 040000033
G Code: 000045
uj5u.com熱心網友回復:
您可以通過找到問題中未給出的父標簽來獲取全文,然后通過.text一些格式化操作(例如洗掉空行)訪問其字串內容。
BeautifulSouphtml如果在我的示例中丟失,請始終添加標簽soup.html。假設您知道,替換soup.find_all(my parent tag)應該可以修復它。
html = '''
<b>Doc Type: </b>AABB
<br />
<b>Doc No: </b>BBBBF
<br />
<b>System No: </b>aaa bbb
<br />
<b>VCode: </b>040000033
<br />
<b>G Code: </b>000045
<br />
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
parent_tag = soup.html
s = '\n'.join(line for line in parent_tag.text.split('\n') if line != '')
print(s)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/448373.html
