Python Beautifulsoup Getting Attribute Value

家住魔仙堡 提交于 2020-01-04 08:37:06

问题


I'm having difficulty getting the proper syntax to extract the value of an attribute in Beautifulsoup with HTML 5.0.

So I've isolated the occurrence of a tag in my soup using the proper syntax where there is an HTML 5 issue:

tags = soup.find_all(attrs={"data-topic":"recUpgrade"})

Taking just tags[1]:

date = tags[1].find(attrs={"data-datenews":True})

and date here is:

<span class="invisible" data-datenews="2018-05-25 06:02:19" data-idnews="2736625" id="horaCompleta"></span>

But now I want to extract the date time "2018-05-25 06:02:19". Can't get the syntax.

Insight/help please.


回答1:


You can access the attrs using key-value pair

Ex:

from bs4 import BeautifulSoup
s = """<span class="invisible" data-datenews="2018-05-25 06:02:19" data-idnews="2736625" id="horaCompleta"></span>"""
soup = BeautifulSoup(s, "html.parser")
print(soup.span["data-datenews"])

Output:

2018-05-25 06:02:19


来源:https://stackoverflow.com/questions/50533363/python-beautifulsoup-getting-attribute-value

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