美丽汤过滤 包含一个类而不是另一个类



我想过滤包含"class"而不是"style"的脚本,并且我不想使用 set,因为它不会返回正确的答案。下面是脚本:

<p class="price hidden-xs" style="width:100%">-</p>

我使用以下代码:

milage = soup.find_all('p', {'class' : 'price hidden-xs'})

我该如何解决这个问题?

您可以简单地过滤掉具有条件列表推导式的style属性的元素:

from bs4 import BeautifulSoup
markup = (
    '<p id="with_style" class="price hidden-xs" style="width:100%">-</p>'
    '<p id="without_style" class="price hidden-xs">-</p>'
)
soup = BeautifulSoup(markup, "html.parser")
print(
    [
        e
        for e in soup.find_all("p", {"class": "price hidden-xs"})
        if not e.has_attr("style")
    ]
)

结果:

[<p class="price hidden-xs" id="without_style">-</p>]

你可以简单地做:

milage = soup.find_all('p', {'class' : 'price hidden-xs', 'style' : False})

这应该为您提供所有带有class = price hidden-xsp标签,而没有带有style属性的标签。

↳ BS : 基本的查找方法

您可以使用fromstring并在 xPath 表达式中指定 not style 属性

#import requests
from lxml.html import fromstring
# url = ''
# tree = html.fromstring( requests.get(url).content)
h = '''
 <p class="price hidden-xs" style="width:100%">Not me</p>
 <p class="price hidden-xs">Me</p>
'''
tree = fromstring(h)
items = [item.text for item in tree.xpath("//p[@class='price hidden-xs' and not(@style)]")]
print(items)

相关内容

最新更新