【问题标题】:How to get meta tag value with BeautifulSoup soup.select如何使用 BeautifulSoup soup.select 获取元标记值
【发布时间】:2021-05-11 10:45:01
【问题描述】:

我想从一个 html 标签中提取日期。我正在使用 Python 和 Beautiful Soup。

<meta name="Email" content="info@info.de">
<meta name="Date" content="2021-04-28T20:35:00+02:00">
<meta name="title" content="Tris is tite">

我只想提取日期,所以这应该是结果:2021-04-28T20:35:00+02:00

我知道我可以这样做:

tag = "meta['Date']"
date = soup.select(tag)
date = date['content']

但是是否可以仅使用一个 css 选择器,仅使用标签值来做到这一点? 例如,像这样的东西?

tag = "meta['Date']['content']" # or something like this?
date = soup.select(tag)
print(date)
2021-04-28T20:35:00+02:00

PS 我必须使用soup.selectsoup.find(...)soup.select_one 对我不起作用。 所以只有soup.select 有效!

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    你快到了。您似乎混淆了属性名称。试试:

    tag = "meta[content]" 
    date = soup.select_one(tag)
    print(date.get('content'))
    

    输出:

    2021-04-28T20:35:00+02:00
    

    编辑: 将标语行更改为:

    tag = "meta[content][name='Date']" 
    

    【讨论】:

    • 我已经更新了我的问题,也许我应该早点指出有很多元标签,我只想要日期标签
    【解决方案2】:

    你可以简单地使用:

    >>> from bs4 import BeautifulSoup
    >>> content = """<meta name="Date" content="2021-04-28T20:35:00+02:00"> """
    >>> soup = BeautifulSoup(content, 'html.parser')
    >>> soup.find("meta", {"name": "Date"}).attrs['content']
    >>> '2021-04-28T20:35:00+02:00'
    

    如果您想提取所有“元”标签并使用“选择”显示日期属性:

    >>> for item in soup.select("meta"):
    ...     print(item.attrs.get('content'))
    

    【讨论】:

    • 我必须使用soup.select、soup.find(...) 和soup.select_one 对我不起作用。所以只有soup.select 有效我正在寻找soup.select 的解决方案
    猜你喜欢
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    相关资源
    最近更新 更多