Get content from certain tags with certain attributes using BS4

给你一囗甜甜゛ 提交于 2021-02-11 15:31:15

问题


I need to get the content from the following tag with these attributes: <span class="h6 m-0">. An example of the HTML I'll encounter would be <span class="h6 m-0">Hello world</span>, and it obviously needs to return Hello world.

My current code is as follows:

page = BeautifulSoup(text, 'html.parser')
names = [item["class"] for item in page.find_all('span')]

This works fine, and gets me all the spans in the page, but I don't know how to specify that I only want those with the specific class "h6 m-0" and grab the content inside. How will I go about doing this?


回答1:


page = BeautifulSoup(text, 'html.parser')
names = page.find_all('span' , class_ = 'h6 m-0')

Without knowing your use case I don't know if this will work.




回答2:


names = [item["class"] for item in page.find_all('span',class_="h6 m-0" )]

can you please be more specific about what problem you face

but this should work fine for you



来源:https://stackoverflow.com/questions/62737471/get-content-from-certain-tags-with-certain-attributes-using-bs4

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