Python Beautifulsoup Find_all除外

时间:2016-01-31 15:14:54

标签: python python-3.x beautifulsoup html-parsing

我很难找到解决这个问题的简单方法,并希望你能够提供帮助。

我一直在使用Beautifulsoup找到所有并尝试使用一些正则表达式来查找除下面html中'emptyLine'行以外的所有项目:

(defn add-to-map [y]
  (let [x (sort-string (str/lower-case y))
        my-hash-map (hash-map)]
    (if-not (contains? my-hash-map x)
     (hash-map x, y)
      (hash-set y))
    (if-not (get hash-map x) y)
      ;;remove from hash-set to do...
      ))

是否有一种简单的方法可以找到除了包括'emptyItem'之外的所有项目?

1 个答案:

答案 0 :(得分:3)

只需跳过包含emptyItem类的元素。工作样本:

from bs4 import BeautifulSoup

data = """
<div>
    <div class="product_item0">test0</div>
    <div class="product_item1">test1</div>
    <div class="product_item2">test2</div>
    <div class="product_item2 emptyItem">empty</div>
</div>
"""

soup = BeautifulSoup(data, "html.parser")

for elm in soup.select("div[class^=product_item]"):
    if "emptyItem" in elm["class"]:  # skip elements having emptyItem class
        continue

    print(elm.get_text())

打印:

test0
test1
test2

请注意,div[class^=product_item]是一个CSS选择器,可以匹配所有div元素,其中一个类以product_item开头。