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

2024-05-15 23:10:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从以下网站提取标题和说明:

查看源: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." />

我想要标题和元内容。

我用过鹅,但提取效果不好。这是我的代码:

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] 

结果是空的


Tags: andnameinurl标题fortitleextract
2条回答

请检查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.']

你知道html-xpath吗? 使用lxml lib和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()

相关问题 更多 >