Beautifulsoup find the tag and attribute of without value?

只谈情不闲聊 提交于 2019-12-20 07:30:04

问题


I'm trying to get the content of the particular tag which having the attribute but no values. How can I get it for example

cont = '<nav></nav> <nav breadcrumbs> <a href="">aa</a></nav> <nav></nav>'

From the above one I want to extract the <nav breadcrumbs> <a href="">aa</a></nav>

So I have tried the following one

bread = contSoup.find("nav",{"breadcrumbs":""})

I have tried below one also

bread = contSoup.find("nav breadcrumbs")

Finally I'm using RegEx to get this data, I'm able to get the answer, but how can I do it from the beautiful soup


回答1:


You can use attr=True for this case.

cont = '<nav></nav> <nav breadcrumbs> <a href="">aa</a></nav> <nav></nav>'
soup = BeautifulSoup(cont, 'lxml')  # works with 'html.parser' too.
print(soup.find('nav', breadcrumbs=True))
# which is the same as print(soup.find('nav', {'breadcrumbs': True}))

Output:

<nav breadcrumbs=""> <a href="">aa</a></nav>


来源:https://stackoverflow.com/questions/49205643/beautifulsoup-find-the-tag-and-attribute-of-without-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!