2016-06-24 65 views
2

我想提取从以下网站的标题和描述:如何使用python从URL中提取元描述?

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

我想要的标题和meta内容。

我用鹅,但它没有做好提取。这里是我的代码:

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] 

结果是空

+0

BeautifulSoup怎么样? - https://www.crummy.com/software/BeautifulSoup/ –

回答

4

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

你知道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() 
相关问题