抓住美丽的汤元内容

lme*_*ato 0 python beautifulsoup

我需要在这里使用正则表达式吗?

我想要的内容如下所示:

<meta content="text I want to grab" name="description"/>
Run Code Online (Sandbox Code Playgroud)

但是,有许多以“ meta content =“开头的对象,我想要以name =” description“结尾的对象。我是regex的新手,但我认为BS可以解决这个问题。

zvo*_*one 5

假设您能够将HTML内容读入一个变量并将其命名为html,则必须使用beautifulsoup解析HTML:

from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
Run Code Online (Sandbox Code Playgroud)

然后,要搜索<meta content="text I want to grab" name="description"/>,您必须找到具有名称'meta'和属性的标签name='description'

def is_meta_description(tag):
    return tag.name == 'meta' and tag['name'] == 'description'

meta_tag = soup.find(is_meta_description)
Run Code Online (Sandbox Code Playgroud)

您正在尝试获取content标签的属性,因此:

content = meta_tag['content']
Run Code Online (Sandbox Code Playgroud)

由于这是一个简单的搜索,因此还有一种更简单的方法来找到标签:

meta_tag = soup.find('meta', attrs={'name': 'description'})
Run Code Online (Sandbox Code Playgroud)