【发布时间】:2024-05-27 22:40:01
【问题描述】:
我有这个跨度,我想得到标题
<span title="Something"></span>
如何用beautifulsoup 获得它?
res = soup.find('span')
print res //Was trying to add res.title but result is 'None'
【问题讨论】:
标签: python python-2.7 beautifulsoup
我有这个跨度,我想得到标题
<span title="Something"></span>
如何用beautifulsoup 获得它?
res = soup.find('span')
print res //Was trying to add res.title but result is 'None'
【问题讨论】:
标签: python python-2.7 beautifulsoup
你应该可以像这样访问它:
res = soup.find('span')['title']
编辑:我应该澄清一下, res 将是 title 属性的值。如果您希望以后使用该元素,请将我的代码更改为:
res = soup.find('span')
title = res['title']
那么您可以继续使用res(如果需要)。
另外,.find 将返回单个元素。您需要确保它是您想要的跨度,因为 HTML 可能有多个跨度。
【讨论】:
这是文档的内容:
soup.findAll(['title', 'p'])
# [<title>Page title</title>,
# <p id="firstpara" align="center">This is paragraph <b>one</b>.</p>,
# <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>]
soup.findAll({'title' : True, 'p' : True})
# [<title>Page title</title>,
# <p id="firstpara" align="center">This is paragraph <b>one</b>.</p>,
# <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>]
您也可以使用正则表达式。
【讨论】: