how do i grab first link from out put

32 Views Asked by At
`enter code here`
from bs4 import BeautifulSoup
import requests

url = "https://www.tutorialspoint.com/index.htm"
req = requests.get(url)
soup = BeautifulSoup(req.text, "html.parser")

for link in soup.find_all('a'):
    print(str(link.get('href')))

this is the out put

https://www.tutorialspoint.com/index.htm https://www.tutorialspoint.com/codingground.htm https://www.tutorialspoint.com/about/about_careers.htm

  1. i need to know how do i grab first link

    https://www.tutorialspoint.com/index.htm

2

There are 2 best solutions below

3
On

Just index the list.

links = soup.find_all('a')[0].get('href')

out

https://www.tutorialspoint.com/index.htm
2
On

you can use find instead it only gets the first element

link = soup.find('a').get('href')