python - BeautifulSoup: searching for multiple tags
问题描述
I'm currently implementing Beautiful Soup in my application to search through a user's HTML content. How it works is that if the user does not input one of the HTML tags specified, it returns a false value. This works fine when there is only one HTML tag, however I also want this to work for multiple HTML tags. Here is my code.
soup = BeautifulSoup(userInput, 'html.parser')
if soup.find(['h1','h2']) is None:
return false
else:
return true
So how I want it to work is that if all elements in the array [h1,h2] are not in the user input, then it will return false. How the code above is functioning is that if the user enters one of the values in the array it will return true.
Is there any way to implement this in Python?
解决方案
.find
不能这样工作。您必须为每个标签调用一次:
if not any(soup.find(tag) for tag in ('h1', 'h2')):
# if inputted HTML does not contain h1 or h2 tags
您当然可以使用您需要的任何逻辑。如果要强制同时存在h1
和h2
标签,请使用
if not all(soup.find(tag) for tag in ('h1', 'h2'))
推荐阅读
- python - 使用 python 的 iterparse 有效地过滤 XML 元素
- testing - 我正在使用 Testcafe : Settings.json 文件。节点模块中显示的错误
- python - FFMPEG + Python - 在 ffmpeg 端跳过不需要的帧
- python - 当它的值可以在另一列中时如何处理空行?
- php - PHP 无法将验证码字符串与用户输入的字符串进行比较
- python-3.x - PYGAME - 外部类的 Blit 不起作用
- actions-on-google - 设备名称显示为“??”
- php - 如何根据登录用户在 php 中从 MySQL 获取特定用户数据
- python - 蟒蛇,基维。如何禁用/启用按钮?
- javascript - 材质ui输入类型号重置错误值