【问题标题】:How to access tag's attribute value with BeautifulSoup如何使用 BeautifulSoup 访问标签的属性值
【发布时间】:2019-12-29 23:22:09
【问题描述】:

我正在使用 BeautifulSoup 并请求网络抓取。我知道如何提取标签之间的属性,但是如果我想要的是标签中下面的数字'4.31',知道如何获取它吗?

<div class="starRating" title="4.31">
<svg
 ...
</svg>
</div>

我试过了:

soup.find('div',{'class':'starRating'})
soup.find('title')

什么都不返回,所以数字基本上就是标签...

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    你可以像这样读取属性title的值:

    from bs4 import BeautifulSoup
    
    
    response = """
    <html>
    <div class="starRating" title="4.31">
    <svg>
    </svg>
    </div>
    </html>
    """
    
    soup = BeautifulSoup(response, 'lxml')
    print(soup.find('div', {'class': 'starRating'})['title'])
    

    输出:

    4.31
    

    https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes `

    一个标签可以有任意数量的属性。标签&lt;b id="boldest"&gt; 有一个属性“id”,其值为“boldest”。您可以通过将标签视为字典来访问标签的属性

    【讨论】:

      【解决方案2】:

      您可以使用 lambda 查询具有匹配 title 属性的元素,然后使用 ["title"] 键提取您想要的数据:

      >>> soup.find(lambda x: x.name == "div" and "title" in x.attrs)["title"]
      '4.31'
      

      或者使用 CSS 选择器:

      >>> soup.select_one("div[title]")
      <div class="starRating" title="4.31"></div>
      

      更简单,使用 target 属性作为 kwarg:

      >>> soup.find("div", title=True)
      <div class="starRating" title="4.31"></div>
      

      尝试将title 属性从没有它的元素中拉出会引发KeyError,因此值得提前过滤。如果您想要多个结果的可迭代,请使用 find_allselect

      【讨论】: