CarterB
CarterB

Reputation: 542

Scraping certain URL from specific page

I am trying to scrape all URLS from a page, which specifically relate to one topic.

I am using beautiful soup to do this.

My current attempt is

urls = soup.find_all('a', href=True)

But there are many extra URLS on the page I do not want to scrape.

The page is: https://www.basketball-reference.com/players/

And I want to scrape all player names as well as their reference code, for example

 <a href="/players/a/allenra02.html">Ray Allen</a>,

would add 'Ray Allen/allenra02 to a list.

How do I add a required prefix to a url search using beautiful soup? for example 'players/'

Upvotes: 0

Views: 84

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195468

You can use compiled regex as href= parameter in .find_all().

For example:

import re
import requests
from bs4 import BeautifulSoup


url = 'https://www.basketball-reference.com/players/'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

r = re.compile(r'/players/.+/(.*?)\.html')
out = []
for a in soup.find('ul', class_="page_index").find_all('a', href=r):
    out.append('{}/{}'.format(a.get_text(strip=True), r.search(a['href']).group(1)))

from pprint import pprint
pprint(out)

Prints:

['Kareem Abdul-Jabbar/abdulka01',
 'Ray Allen/allenra02',
 'LaMarcus Aldridge/aldrila01',
 'Paul Arizin/arizipa01',
 'Carmelo Anthony/anthoca01',
 'Tiny Archibald/architi01',
 'Charles Barkley/barklch01',
 'Kobe Bryant/bryanko01',
 'Larry Bird/birdla01',
 'Walt Bellamy/bellawa01',
 'Rick Barry/barryri01',
 'Chauncey Billups/billuch01',
 'Wilt Chamberlain/chambwi01',
 'Vince Carter/cartevi01',
 'Maurice Cheeks/cheekma01',
 'Stephen Curry/curryst01',

...and so on.

Upvotes: 1

sushanth
sushanth

Reputation: 8302

try this,

import requests

url = 'https://www.basketball-reference.com/players/'
soup = BeautifulSoup(requests.get(url).text, "html.parser")

ul = soup.find("ul", attrs={'class':"page_index"})

for li in ul.findAll("li"):
    # ignore the first value (index A,B...)
    for player in li.select("a")[1:]:
        print(
            player.text + "/" + player['href'].split("/")[-1].replace(".html", "")
        )

Kareem Abdul-Jabbar/abdulka01
Ray Allen/allenra02
LaMarcus Aldridge/aldrila01
...
...

Upvotes: 1

Related Questions