我需要帮助从脚本结果中解析出 HTML
标记。我想将结果放入一个对象中以转换为 json。当我打印对象时,一切正常,除了我无法提取没有 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 标签的对象形式的结果。
根据评论更新:
我当前看到的结果只是打印上面的代码:
{'name': <a href="/team/001"> Team 1 </a>, 'description': <p><a href="/team/001">Team 1</a> is a team does cool things.</p>}
更新代码以包含.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()
,所以这与上面的评论类似,但我认为您希望获得上次搜索中的文本结果。
如果需要传入格式化参数,可以使用 get_text()。 See the docs
编辑:
收到 NoneType 错误告诉我您有一些 <tr>
不包含 <a>
的标签或<p>
内标记。如果record.find在循环中找不到结果,那么它将返回None,它不能返回文本值。
您可以用逻辑来解决这个问题,或者重新评估您进行搜索的方式。黑客的方法是在返回文本之前检查是否有所需的标签。
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
}
关于python - BeautifulSoup 和 Python 删除 HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58821590/