使用BeautifulSoup获取span类名



我正在使用BeautifulSoup来抓取一个网站。检索到的结果集如下所示:

<td><span class="I_Want_This_Class_Name"></span><span class="other_name">Text Is Here</span></td>

从这里,我想检索类名";I_Want_His_Class_Name";。我可以得到";文本在这里"部分没有问题,但是类名本身被证明是困难的。

有没有一种方法可以使用BeautifulSoup结果集来实现这一点,或者我需要转换为词典?

谢谢

from bs4 import BeautifulSoup
doc = '''<td><span class="I_Want_This_Class_Name"></span><span class="other_name">Text Is Here</span></td>
'''
soup = BeautifulSoup(doc, 'html.parser')
res = soup.find('td')
out = {}
for each in res:
if each.has_attr('class'):
out[each['class'][0]] = each.text
print(out) 

输出将类似于:

{'I_Want_His_Class_Name':'','other_Name':'Text Is Here'}

如果你试图获得这个结果的类名,那么我会在你的汤对象上使用select方法,调用类键:

foo_class = soup.select('td>span.I_Want_This_Class_Name')[0]['class'][0]

请注意,select方法确实返回了一个列表,因此在键之前进行了索引。

最新更新