【问题标题】:Beautiful Soup : How to get data which matches any of the given stringBeautiful Soup:如何获取与任何给定字符串匹配的数据
【发布时间】:2019-11-09 13:40:21
【问题描述】:
我正在尝试找出可以匹配任何输入字符串的元素。
例如:-
data = soup.find(text="something")
这很好用,但是当我必须搜索这样的东西时如何使用它:-
data = soup.find(text="something" or text="another something")
如果不可能搜索多个字符串,那么执行类似操作的最佳方法应该是什么。
【问题讨论】:
标签:
python
python-3.x
python-2.7
beautifulsoup
html-parsing
【解决方案1】:
Regex 无疑是搜索多个文本的有效且有用的方法,但人们经常忘记(或不知道)您可以传入字符串列表,Beautiful Soup 将返回与名单:
from bs4 import BeautifulSoup
html = """
<div>something</div>
<div>something else</div>
"""
soup = BeautifulSoup(html, "lxml")
items = soup.find_all(text=["something", "something else"])
print(items)
输出
['something', 'something else']
【解决方案2】:
您可以在此处使用正则表达式。
例如:
import re
data = soup.find(text=re.compile("something|another something"))