[英]Searching for pieces of an attribute with Beautiful Soup
我想使用Beautiful Soup提取具有以下格式的所有內容:
div class="dog-a b-cat"
如果我通過執行以下操作來知道“ a”和“ b”是什么,則可以得到一個特定實例(假設a=aardvark
和b=boy
):
soup.find_all("div",class_="dog-aardvark boy-cat")
有什么辦法可以拉出所有實例(無論破折號之間的兩個字如何),其中有dog和cat以及介於兩者之間的兩個破折號?
@ bourbaki4481472總體上是正確的,但是由於多種原因,建議的解決方案將不起作用,因為指定的正則表達式將一次與單個類進行匹配 ,因為class
是特殊的多值屬性,而結束在語法上根本不正確 。
我建議您創建一個過濾函數 ,以檢查第一個類的值以dog-
開頭,第二個以-cat
結尾。 您可以通過另外檢查標記名稱或如果需要的話提供多少類值來改進它:
def class_filter(elm):
try:
classes = elm["class"]
return classes[0].startswith("dog-") and classes[1].endswith("-cat")
except (KeyError, IndexError, TypeError):
return False
完整的例子:
from bs4 import BeautifulSoup
data = """
<div class="dog-test test-cat">test1</div>
<div class="dog-test">test2</div>
<div class="test-cat">test3</div>
<div class="dog">test4</div>
<div class="cat">test5</div>
<div class="irrelevant">test6</div>
"""
soup = BeautifulSoup(data)
def class_filter(elm):
try:
classes = elm["class"]
return classes[0].startswith("dog-") and classes[1].endswith("-cat")
except (KeyError, IndexError, TypeError):
return False
for elm in soup.find_all(class_filter):
print(elm.text)
僅打印test1
。
嘗試使用正則表達式來概括您的參數。
import re
soup.find_all("div", class= re.compile(r"dog-.+ boy-.+")
上面的代碼將查找字符串dog-
后跟一個或多個字符,然后是[space],然后是boy-
然后是一個或多個字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.