Python 移除所有';b';html脚本中的标记及其内容
当我想尝试去掉所有的b标签和它们的内容,只留下剩下剩下的文本时,我正在使用BeautifulSoup和玩史莱克脚本来适应它Python 移除所有';b';html脚本中的标记及其内容,python,beautifulsoup,Python,Beautifulsoup,当我想尝试去掉所有的b标签和它们的内容,只留下剩下剩下的文本时,我正在使用BeautifulSoup和玩史莱克脚本来适应它 import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent url = "https://www.imsdb.com/scripts/Shrek.html" ua = UserAgent(verify_ssl=False) headers = {'
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
url = "https://www.imsdb.com/scripts/Shrek.html"
ua = UserAgent(verify_ssl=False)
headers = {'User-Agent': 'ua.chrome'}
def get_script():
script_text = requests.get(url, headers=headers)
soup = BeautifulSoup(script_text.text, 'html.parser')
script = soup.find('td', class_='scrtext')
tag = script.find_all('b')
if tag is None:
pass
else:
tag.clear()
print(tag)
get_script()
这是我使用的代码
如果要注释掉If和else语句并运行代码,id将显示所有b标记及其内容,如果要取消注释并运行它,它将返回[]
。所以标签被删除了。问题是,当我使用print(script)
而不是print(tag)
时,它只是正常返回脚本,而不删除任何b标记或其内容,即使它们已被删除
有人知道为什么吗?要删除
标记,您应该像这样使用.extract()
:
for b in soup.find_all('b'):
b.extract()
Nvm你所要做的就是
for b in tag:
b.clear()
b.decompose()
这将删除所有b标签及其内容,同时保留脚本的其余部分不变,这正是我想要的。你到底想从网站上刮取什么?没有标签的脚本文本及其内容OK…那么其中的文本呢?我回答了自己,以便你能看到我在说什么