我的目標:嘗試構建一個函式;def retrieve_title(html)期望作為輸入,一個 html 字串并回傳標題元素。
我已經匯入了beautifulsoup 來完成這個任務。感謝任何指導,因為我仍在學習。
我嘗試的功能:
def retrieve_title(html):
soup = [html]
result = soup.title.text
return(result)
使用功能:
html = '<title>Jack and the bean stalk</title><header>This is a story about x y z</header><p>talk to you later</p>'
print(get_title(html))
意想不到的結果:
“AttributeError:‘list’物件沒有屬性‘title’”
預期結果:
“杰克與魔豆”
uj5u.com熱心網友回復:
Jack and the bean stalk是緊隨其后的文本節點,title tag以便您可以應用.find(text=True)
html = '''
<title>
Jack and the beanstalk
</title>
<header>
This is a story about x y z
</header>
<p>
Once upon a time
</p>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'html.parser')
#print(soup.prettify())
title=soup.title.find(text=True)
print(title)
輸出:
Jack and the beanstalk
uj5u.com熱心網友回復:
你必須呼叫函式
print(retrieve_title(html))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/462906.html
下一篇:將python輸出捕獲到變數
