H
H
HEnl2020-08-09 19:43:25
Python
HEnl, 2020-08-09 19:43:25

How to get first href from div?

Like from

<div class="dots-item"><a href="/index.php?r=crop/harvest&amp;id=12245218"><img alt="Z" height="50" src="https://static/light/crops/gas_station.png" width="50"/></a><a href="/index.php?r=crop/harvest&amp;id=12245218"><img alt="Harvest" class="crop_ico" src="https://static/i/../light/dots/st/dot-st-ready.png"/></a></div>

get ? tried like this:
url = '/index.php?r=crop/harvest&amp;id=12245218'
divs

divs = [<div class="dots-item"><a href="/index.php?r=crop/harvest&amp;id=12245218"><img alt="z" height="50" src="https://static.hata.mobi/light/crops/gas_station.png" width="50"/></a><a href="/index.php?r=crop/harvest&amp;id=12245218"><img alt="Harvest" class="crop_ico" src="https://static/i/../light/dots/st/dot-st-ready.png"/></a></div>,     <div class="dots-item"><a href="/index.php?r=crop/harvest&amp;id=12245219"><img alt='zz"' height="50" src="https://static/light/crops/dining.png" width="50"/></a><a href="/index.php?r=crop/harvest&amp;id=12245219"><img alt="Harvest" class="crop_ico" src="https://static/i/../light/dots/st/dot-st-ready.png"/></a></div>]


divs['href']



but it didn't work out

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin ™, 2020-08-09
@markbrutx

Works on your piece of code. Checked :)
If this answer helped you, mark it as solved.

#!/usr/bin/env python3

import requests
from bs4 import BeautifulSoup

html = '<div class="dots-item"><a href="/index.php?r=crop/harvest&amp;id=12245218"><img alt="Z" height="50" src="https://static/light/crops/gas_station.png" width="50"/></a><a href="/index.php?r=crop/harvest&amp;id=12245218"><img alt="Harvest" class="crop_ico" src="https://static/i/../light/dots/st/dot-st-ready.png"/></a></div>'


soup = BeautifulSoup(html, 'html.parser')

href = soup.find('div', attrs = {'class':'dots-item'}).find('a').get('href')

print(href)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question