如何使用Python从URL中提取元描述信息?

12

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

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] 

结果为空


美味汤怎么样?- https://www.crummy.com/software/BeautifulSoup/ - Bubble Hacker
4个回答

22
请使用以下代码从上述问题中提取“描述”信息:

请使用以下代码从上述问题中提取“描述”信息:

请检查BeautifulSoup作为解决方案。

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.']

1
你可能想要添加检查 meta.attrs 中是否存在内容的代码,因为格式不正确的 HTML 可能会导致抛出异常: [meta.attrs['content'] for meta in metas if 'name' in meta.attrs and 'content' in meta.attrs and meta.attrs['name'] == 'description'] - Marius Tibeica
你可能想在打印语句中添加括号()。 - Elvin Aghammadzada

1

你是否了解HTML XPath?使用lxml库和XPath提取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()

0

导入metadata_parser

页面 = metadata_parser.MetadataParser(url='www.xyz.com') metaDesc=页面.metadata['og']['description'] print(metaDesc)


虽然这段代码可能解决了问题,但是包括解释它如何以及为什么解决了问题将有助于提高您的帖子质量,并可能导致更多的赞。请记住,您正在回答未来读者的问题,而不仅仅是现在提问的人。请[编辑]您的答案以添加解释并指出适用的限制和假设。 - Yunnosch

0
你可以使用BeautifulSoup来实现这个功能。
应该会有帮助 -
metas = soup.find_all('meta') #Get Meta Description
for m in metas:
    if m.get ('name') == 'description':
        desc = m.get('content')
        print(desc)
        

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接