如何使用 python 从 url 中提取元描述?

How to extract meta description from urls using python?

我想从以下网站提取标题和描述:

view-source:http://www.virginaustralia.com/au/en/bookings/flights/make-a-booking/

使用以下源代码片段:

<title>Book a Virgin Australia Flight | Virgin Australia
</title>
    <meta name="keywords" content="" />
        <meta name="description" content="Search for and book Virgin Australia and partner flights to Australian and international destinations." />

我想要标题和元内容。

我用了 goose,但提取效果不佳。这是我的代码:

website_title = [g.extract(url).title for url in clean_url_data]

website_meta_description=[g.extract(urlw).meta_description for urlw in clean_url_data] 

结果为空

请检查 BeautifulSoup 作为解决方案。

对于上述问题,您可以使用以下代码提取"description"信息:

import requests
from bs4 import BeautifulSoup

url = 'http://www.virginaustralia.com/au/en/bookings/flights/make-a-booking/'
response = requests.get(url)
soup = BeautifulSoup(response.text)

metas = soup.find_all('meta')

print [ meta.attrs['content'] for meta in metas if 'name' in meta.attrs and meta.attrs['name'] == 'description' ]

输出:

['Search for and book Virgin Australia and partner flights to Australian and international destinations.']

你知道 html xpath 吗? 使用带有 xpath 的 lxml 库来提取 html 元素是一种快速的方法。

import lxml

doc = lxml.html.document_fromstring(html_content)
title_element = doc.xpath("//title")
website_title = title_element[0].text_content().strip()
meta_description_element = doc.xpath("//meta[@property='description']")
website_meta_description = meta_description_element[0].text_content().strip()

金额metadata_parser

页数=metadata_parser.MetadataParser(url='www.xyz.com') metaDesc=page.metadata['og']['description'] 打印(元描述)

您可以使用 BeautifulSoup 来实现。

应该会有帮助 -

metas = soup.find_all('meta') #Get Meta Description
for m in metas:
    if m.get ('name') == 'description':
        desc = m.get('content')
        print(desc)