【问题标题】:Get span title using beautifulsoup使用 beautifulsoup 获取 span 标题
【发布时间】: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


    【解决方案1】:

    你应该可以像这样访问它:

    res = soup.find('span')['title']

    Docs

    编辑:我应该澄清一下, res 将是 title 属性的值。如果您希望以后使用该元素,请将我的代码更改为:

    res = soup.find('span')
    title = res['title']
    

    那么您可以继续使用res(如果需要)。

    另外,.find 将返回单个元素。您需要确保它是您想要的跨度,因为 HTML 可能有多个跨度。

    【讨论】:

    【解决方案2】:

    这是文档的内容:

    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>]
    

    您也可以使用正则表达式。

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签