![](/img/trans.png)
[英]How to extract SRC attribute from IMG tag with BeautifulSoup?
[英]How to extract attribute value from a tag in BeautifulSoup
我正在嘗試從標簽(在本例中為TD
)中提取屬性的值。 代碼如下(HTML文檔加載正確; self.data
包含帶有HTML數據的字符串,該方法是類的一部分):
def getLine (self):
dat = BeautifulSoup(self.data, "html.parser")
tags = dat.find_all("tr")
for current in tags:
line = current.findChildren("td", recursive=False)
for currentLine in line:
# print (currentLine)
clase = currentLine["class"] # <-- PROBLEMATIC LINE
if clase is not None and "result" in clase:
valor = Line()
valor.name = line.text
錯誤出現在clase = currentLine["class"]
行中。 我只需要檢查標簽元素是否具有此屬性並執行操作以防它具有值"result"
。
File "C:\DataProgb\urlwrapper.py", line 43, in getLine
clase = currentLine["class"] #Trying to extract attribute class
\AppData\Local\Programs\Python\Python39\lib\site-packages\bs4\element.py", line 1519, in __getitem__
return self.attrs[key]
KeyError: 'class'
它應該可以工作,因為它只是一個元素。 我不明白這個錯誤。 謝謝。
主要問題是您嘗試直接訪問屬性鍵,如果屬性不可用,將返回KeyError
:
currentLine["class"]
而是使用get()
,它實際上將返回缺少的屬性None
:
currentLine.get("class")
從文檔 - get(key\[, default\])
:
如果鍵在字典中,則返回鍵的值,否則返回默認值。 如果未給出默認值,則默認為無,因此此方法永遠不會引發 KeyError。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.