![](/img/trans.png)
[英]How can I find_all or select multiple attribute names using Beautiful Soup?
[英]beautiful soup find_all, encompassing multiple class names
我試圖在 for 循環中使用 beautifulsoup find_all 函數來返回具有不同類的兩個 td 元素之一。 td 元素位於 html div 元素內。 有多個 div 被 for 循環迭代,每個 div 將保存兩個具有不同類的 td 元素之一。
我的目標是從 td 元素中獲取文本,但我無法找到一種方法來實現它,因此 find_all 函數可以接受兩個 td 類。
我想使用一個 find_all 來獲取這些 td 元素中的任何一個,無論當前 div 元素中存在哪個。
示例 html 如下所示:
<div> <td class='class1'> text to scrape </td> </div> <div> <td class='class2'> text to scrape </td> </div>
我的代碼看起來像這樣:
for propbox in soup.find_all('div')
tester = propbox.find_all('td', {"class" : lambda A: A.contains("class1") or A.contains("class2")})
我收到一個錯誤:AttributeError: 'NoneType' object has no attribute 'contains'
所以我由此假設,當一個 td 類不存在時,python 仍在嘗試在它不喜歡的 None 類型上使用 .contains() 。
有誰知道我可以實現這一目標的方法? 非常感謝任何幫助/示例。 提前致謝
函數被賦予每個class
屬性值( str)
; 然后是整個類的屬性值(除非之前沒有為元素返回調用)。 但是如果沒有class
屬性,則None
是傳遞參數。
所以你需要檢查None
。
或者對你來說簡單in
情況就足夠了:
for propbox in soup.find_all('div'):
tester = propbox.find_all('td', {
"class": lambda class_: class_ in ("class1", "class2")
})
# print(tester)
順便說一句,沒有contains
方法,但__contains__
方法( in
,成員資格測試運算符將使用它):
>>> 'haystack'.contains('needle')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'contains'
>>> 'haystack'.__contains__('needle')
False
>>> 'needle' in 'haystack'
False
>>> 'haystack'.__contains__('hay')
True
>>> 'hay' in 'haystack'
True
我想出了另一種方法來做到這一點,可能不如 falsetru 提出的那樣健壯。
Agenttester = propbox.find_all('td', class_="class2")
if Agenttester == []:
Agenttester = 'This is class1'
else:
Agenttester = 'this is class2'
這在我的情況下也可以正常工作,因為如果 div 中不存在 class2,則它返回 []。 但 falsetru 有正確的想法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.