![](/img/trans.png)
[英]Python beautifulsoup trying to remove html tags 'span'
[英]BeautifulSoup and Python Remove HTML Tags
我需要帮助从我的脚本结果中解析出HTML
标记。 我想将结果放入 object 以转换为 json。 当我打印 object 时,一切正常,除了我不能只提取没有 html 标签的文本。 我一直在这个网站上搜索答案并尝试了各种方法来删除标签,但我不确定我做错了什么。 我很感激任何帮助。
根据我在这里阅读的一些内容,我尝试打印 teamObject.text 但这不起作用。
def make_soup(url):
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
return soup
soup = make_soup("team.html")
for record in soup.findAll('tr'):
teamObject = {"name": record.find('a'),"description": record.find('p')}
print (teamObject)
我希望看到没有 html 标签的 object 形式的结果。
根据评论更新:
我目前看到的结果只是打印我上面的代码:
{'name': <a href="/team/001"> Team 1 </a>, 'description': <p><a href="/team/001">Team 1</a> is a team does cool things.</p>}
将代码更新为 include.text:
def make_soup(url):
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
return soup
soup = make_soup("team.html")
for record in soup.findAll('tr'):
teamObject = {
"name": record.find('a').text,
"description": record.find('p').text
}
print (teamObject)
我得到这个结果:
"name": record.find('a').text,
AttributeError: 'NoneType' object has no attribute 'text'
我希望只看到没有 html 标签的文本。
尝试对循环中每条记录的查找结果使用.text
。
for record in soup.findAll('tr'):
teamObject = {
"name": record.find('a').text,
"description": record.find('p').text
}
.text
调用.get_text()
,所以这类似于上面的评论,但我认为你想在最后一次搜索中获得文本结果。
如果需要传入 arguments 进行格式化,可以使用 get_text() 。 查看文档
编辑:
收到 NoneType 错误告诉我您有一些<tr>
标签,其中不包含<a>
或<p>
标签。 如果record.find在循环中找不到结果,那么它将返回None,它不能返回文本值。
你可以用逻辑解决这个问题,或者重新评估你是如何进行搜索的。 hacky 方法是在返回文本之前检查您是否有所需的标签。
for record in soup.findAll('tr'):
if record.a and record.p:
teamObject = {
"name": record.find('a').text,
"description": record.find('p').text
}
这可以确保您不会收到 None 错误,但现在您将完全跳过任何缺少<a>
或<p>
标记的行,所以要小心。
如果您确信相关行将始终具有<a>
和<p>
标签,则可以通过仅返回包含“Team”的行来集中搜索以排除任何错误的<tr>
条目。
for record in soup.select('tr:contains("Team")'):
teamObject = {
"name": record.find('a').text,
"description": record.find('p').text
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.