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

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

BeautifulSoup 使用類獲取最近的標簽,而不是兄弟姐妹并嵌套在未知兄弟姐妹中

BeautifulSoup 使用類獲取最近的標簽,而不是兄弟姐妹并嵌套在未知兄弟姐妹中

繁星coding 2021-10-19 17:08:22
<h3>    <span></span>    <span class='headline'>Headline #1</span></h3><table class='striped'></table><h4>    <span class='headline'>Headline #2</span></h4><table class='striped'></table><p>    <span class='headline'>Headline #3</span></p><ul></ul><center>    <table class='striped'></table></center>這是我的結構。我正在枚舉表格標簽,并希望使用最接近我的表格的“標題”類檢索跨度標簽的文本值。通過“最近”我的意思是,如果你要展平 html,我想用一個類“標題”來定位跨度,如果你從表格的點開始,你會首先遇到它有時這些跨度嵌套在 h3、有時是 h4、有時是 ap 標簽中。有時 table 標簽與 h3/h4/p 處于同一級別,有時它本身嵌套在 center 標簽內。有時 h3/h4/p 標簽是表的直接兄弟,有時不是。如何使用 BeautifulSoup 查找最近的 span.headline,無論嵌套級別如何以及它是否嵌套在父級或兄弟級中?到目前為止我有這個代碼tables = soup.findAll("table", {"class": ["striped"]})for index, table in enumerate(tables):    headline = table.find_previous('h3').("span", {"class" : ["headline"]}).text
查看完整描述

1 回答

?
LEATH

TA貢獻1936條經驗 獲得超7個贊

我能夠find_previous在每個表上使用該方法來查找您提供的示例 html 的前一個標題。idx在檢查標題是否屬于該表時,我為每個表添加了一個附加屬性。我還在 html 的開頭和結尾添加了兩個沒有以前標題的表格。


html = '''

<table class='striped'></table>

<h3>

    <span></span>

    <span class='headline'>Headline #1</span>

</h3>

<table class='striped'></table>

<h4>

    <span class='headline'>Headline #2</span>

</h4>

<table class='striped'></table>

<p>

    <span class='headline'>Headline #3</span>

</p>

<ul></ul>

<center>

    <table class='striped'></table>

</center>

<table class='striped'></table>

</div>

'''.replace('\n', '')


soup = BeautifulSoup(html, 'lxml')

table_query = ('table', {'class': 'striped'})

headline_query = ('span', {'class': 'headline'})


for idx, table in enumerate(soup.find_all(*table_query)):

    table.attrs['idx'] = idx

    previous_headline = table.find_previous(*headline_query)

    if (previous_headline and 

        previous_headline.find_next(*table_query).attrs['idx'] == idx):

        print(previous_headline.text)

    else:

        print('No headline found.')

輸出:


No headline found.

Headline #1

Headline #2

Headline #3

No headline found.


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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