-4
 articles = contents.find_all('article')
 for article in articles:
     titles=article.find('div',{"class":"featured"})
     print(titles)

This is giving the output as

<div class="featured" style="background-image: url(https://therecipecritic.com/wp-content/uploads/2018/02/Mint-Oreo-Cheesecake-1-of-1-350x500.jpg)"> <a href="https://therecipecritic.com/2018/02/mint-oreo-cheesecake/" rel="bookmark"><span class="readpost">View the Recipe</span></a></div>

Here how can I get the href of the element a

Badhusha
  • 195
  • 2
  • 20
  • 1
    Possible duplicate of [BeautifulSoup getting href](https://stackoverflow.com/questions/5815747/beautifulsoup-getting-href) – Ali Feb 19 '18 at 05:15

3 Answers3

0

You are quite close. You can access the href by accessing the builtin __getitem__ method of the results returned from finding the a attributes:

print(titles.find('a')['href'])
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

You need to access first the a tag and then access it's href attribute like you would with a dictionary:

>>> titles.a['href']
'https://therecipecritic.com/2018/02/mint-oreo-cheesecake/'
Vinícius Figueiredo
  • 6,300
  • 3
  • 25
  • 44
0

Many ways to skin cats with Python. Here is how I do it...

wsHREF = wsArticle.find("<<tag>>", re.compile("<<classname>>.*")).attrs['href']

where 'wsArticle' is my BSoup object of a node of elements, <<tag>> is your HTML tag to find, and <<classname>> is your class to search for, but I use a wildcard to find everything starting with... myclass... etc.

Fandango68
  • 4,461
  • 4
  • 39
  • 74