python-3.x - 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'”?
谢谢
解决方案
如果我正确理解您的问题,您可以简单地执行以下操作:
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())
推荐阅读
- android - 如何在Android Motion Layout中为drawable设置动画
- javascript - Bootstrap 4 Smart Scroll Mobile 菜单在顶部消失
- angular - NGRX 关于如何实现数组数组的困惑
- python-3.x - 无效的 base64 编码字符串:数据字符数 (217) 不能是 1 大于 4 的倍数
- apache-spark - 是否可以注册 DataFrame API 函数以在 SQL 表达式中使用?
- python - 如何使用烧瓶将一个 css 文件包含到另一个文件中?
- aws-lambda - 用于 lambda 的代码管道未部署最新代码
- python - 如何减少pytorch python张量操作中的第二维
- javascript - 包含一个元素的数组,该元素包含许多我想成为数组元素的对象
- flutter - 使用 integration_test 包在颤振集成测试中设置语言环境