尝试用beautiful soup按标签提取网页中的文字,打算提取的文本是台词,所以是想把有格式标签的文字排除在外,比如说人名有的标签,以及描述性动作有的标签。
比如下面这段html代码,希望能过滤掉b和i标签里的内容
<p>
<b>CLINT BARTON:</b>
Okay, now let's worry about how you get there.
<i>
[Clint corrects his daughter's foot to the proper position, and adjusts her shooting stance.]
</i>
<p>
但是哪怕是b和i的标签其实也都是在p的块里,所以我尝试使用attrs的if判断选择似乎完全不起作用……输出的列表似乎还是所有的内容,不知所措……
# read html
path = "C:\\Users\\Desktop\Py\\Endgame.html"
raw = open(path, errors ="ignore", mode = 'r').read()
#get text
soup = BeautifulSoup(raw, "html.parser")
soup.get_text()
#beautiful soup读取html中文本
body = soup.find("div",{"id":"mw-content-text","lang":"en","dir":"ltr"})
para = body.find_all("p")
#尝试读取无格式的台词部分
lines = []
lines = " ".join([p.get_text().strip() for p in para if len(p.attrs)==0])
print(lines)
我太菜了呜呜呜求大神指教