美丽的汤元内容标签

2022-07-01 00:00:00 python beautifulsoup html-parsing html
<meta itemprop="streetAddress" content="4103 Beach Bluff Rd"> 

我必须得到‘4103海滩断崖路’的内容。我正在尝试使用BeautifulSoup完成此操作,因此,我尝试执行以下操作:

soup = BeautifulSoup('<meta itemprop="streetAddress" content="4103 Beach Bluff Rd"> ')

soup.find(itemprop="streetAddress").get_text()

但我得到的结果是一个空字符串,这在打印Soup对象时可能有意义

print soup

我得到的是This:

<html><head><meta content="4103 Beach Bluff Rd" itemprop="streetAddress"/> </head></html>

显然我需要的数据在‘meta content’标记中,我如何获取此数据?


解决方案

soup.find(itemprop="streetAddress").get_text()

您将获得匹配元素的文本。相反,获取"Content"属性值:

soup.find(itemprop="streetAddress").get("content")

这是可能的,因为BeautifulSoup提供了dictionary-like interface to tag attributes:

您可以通过将标记视为词典来访问该标记的属性。

演示:

>>> from bs4 import BeautifulSoup
>>>
>>> soup = BeautifulSoup('<meta itemprop="streetAddress" content="4103 Beach Bluff Rd"> ')
>>> soup.find(itemprop="streetAddress").get_text()
u''
>>> soup.find(itemprop="streetAddress").get("content")
'4103 Beach Bluff Rd'

相关文章