我有這種格式的湯:
<div class = 'foo'>
<table> </table>
<p> </p>
<p> </p>
<p> </p>
<div class = 'bar'>
<p> </p>
.
.
</div>
我想刮掉 table 和 bar div 之間的所有段落。挑戰在于這些之間的段落數量不是恒定的。所以我不能只得到前三段(可能是 1-5 段)。
我如何去分這湯來得到段落。正則運算式起初看起來不錯,但它對我不起作用,因為后來我仍然需要一個湯物件來允許進一步提取。
萬分感謝
uj5u.com熱心網友回復:
您可以選擇您的元素,對其進行迭代siblings,break如果沒有p:
for t in soup.div.table.find_next_siblings():
if t.name != 'p':
break
print(t)
或以其他方式接近您的初始問題 - 選擇<div class = 'bar'>and find_previous_siblings('p'):
for t in soup.select_one('.bar').find_previous_siblings('p'):
print(t)
例子
from bs4 import BeautifulSoup
html='''
<div class = 'foo'>
<table> </table>
<p> </p>
<p> </p>
<p> </p>
<div class = 'bar'>
<p> </p>
.
.
</div>
'''
soup = BeautifulSoup(html)
for t in soup.div.table.find_next_siblings():
if t.name != 'p':
break
print(t)
輸出
<p> </p>
<p> </p>
<p> </p>
uj5u.com熱心網友回復:
如果 html 如圖所示,則只需使用 :not 過濾掉后面的同級 p 標簽
from bs4 import BeautifulSoup
html='''
<div class = 'foo'>
<table> </table>
<p> </p>
<p> </p>
<p> </p>
<div class = 'bar'>
<p> </p>
.
.
</div>
'''
soup = BeautifulSoup(html)
soup.select('.foo > table ~ p:not(.bar ~ p)')
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/496220.html
