首页 > 解决方案 > BS4 用于查找任何标题值

问题描述

我有代码示例如下:

from bs4 import BeautifulSoup 


html = '''
<div _ngcontent-vnr-c286="" class="nui-text-widget nui-widget__header__content-title ng-tns-c286-4 ng-star-inserted" title="SRV-VMWARE-02" style=""> SRV-VMWARE-02 </div>
<div _ngcontent-vnr-c286="" class="nui-text-widget nui-widget__header__content-title ng-tns-c286-16 ng-star-inserted" title="SRV-VMWARE-01" style=""> SRV-VMWARE-01 </div>
'''


soup = BeautifulSoup(html, 'html.parser')
for d in soup:
    test = d.find("div", {"title": "any_title"}).getText()
    print(test)

我的问题是有没有一种方法可以搜索“title=”上的任何值,而我们不必专门定义 title 的值,例如“title='SRV-VMWARE-02'”?

谢谢

标签: python-3.xbeautifulsoup

解决方案


如果我正确理解您的问题,您可以简单地执行以下操作:

from bs4 import BeautifulSoup
import re

html = '''
<div _ngcontent-vnr-c286="" class="nui-text-widget nui-widget__header__content-title ng-tns-c286-4 ng-star-inserted" title="SRV-VMWARE-02" style=""> SRV-VMWARE-02 </div>
<div _ngcontent-vnr-c286="" class="nui-text-widget nui-widget__header__content-title ng-tns-c286-16 ng-star-inserted" title="SRV-VMWARE-01" style=""> SRV-VMWARE-01 </div>
'''
soup = BeautifulSoup(html, 'html.parser')
test = soup.findAll("div", {"title": True})
for t in test:
    print(t.getText())

通过传入True,您可以拉出任何具有该属性的元素title。用于False拉取任何没有该属性的元素。

另外,如果您想根据部分值提取元素,BeautifulSoup 支持 Regex

import re
soup = BeautifulSoup(html, 'html.parser')
test = soup.findAll("div", {"title": re.compile('SRV-VMWARE')})
for t in test:
    print(t.getText())

推荐阅读