How to extract meta description from urls using python?

21.2k Views Asked by At

I want to extract the title and description from the following website:

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

with the following snippet of source code:

<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." />

I want the title and meta content.

I used goose but it does not do a good job extracting. Here is my code:

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

and

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

The result is empty

4

There are 4 best solutions below

2
On BEST ANSWER

Please check BeautifulSoup as solution.

For question above, you may use the following code to extract "description" info:

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

output:

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

You can use BeautifulSoup to achieve this.

Should be helpful -

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

do you know html xpath? use lxml lib with xpath to extract html element is one fast way.

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()
1
On

import metadata_parser

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