[英]Beautiful soup remove superscripts
如何從所有文本中刪除上標? 我下面的代碼可以獲取所有可見的文本,但是腳注的上標使事情變得混亂。 如何刪除它們?
例如, Active accounts (1),(2)
, (1),(2)
是可見的上標。
from bs4 import BeautifulSoup
from bs4.element import Comment
import requests
f_url='https://www.sec.gov/Archives/edgar/data/1633917/000163391718000094/exhibit991prq12018pypl.htm'
def tag_visible(element):
if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
return False
if isinstance(element, Comment):
return False
return True
def text_from_html(body):
soup = BeautifulSoup(body, 'html.parser')
texts = soup.findAll(text=True)
visible_texts = filter(tag_visible, texts)
return u" ".join(t.strip() for t in visible_texts)
html = requests.get(f_url)
text= text_from_html(html.text)
BeautifulSoup函數find_all
返回輸入中所有單個離散HTML元素的列表( find_all
是在BeautifulSoup 4中使用的適當函數,優於findAll
)。 下一個函數filter
遍歷此列表,並刪除其回調例程返回False
。 回調函數將測試每個代碼段的標記名,如果它們在不需要的列表中,則返回False
,否則返回True
。
如果這些上標始終由正確的HTML標記sup
指示,則可以將其添加到回調函數中不需要的列表中。
可能的陷阱是:
sup
,而不是使用僅指定 vertical-align: superscript;
的類或跨度vertical-align: superscript;
在其CSS中;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.