为什么我的网页抓取功能返回一些意想不到的东西?



我的目标:尝试构建一个函数;def retrieve_title(html),期望作为输入,一个html字符串,并返回title元素。

我导入了beautifulsoup来完成这个任务。如有任何指导,我都很感激,因为我还在学习。

My trying function:

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' object没有属性'title'">

预期结果:

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

必须调用函数

print(retrieve_title(html))

最新更新