Andy Ia
Andy Ia

Reputation: 13

python loop requests.get() only returns first loop

Trying to scrape a table from multiple webpages and store in a list. The list prints out the results from the first webpage 3 times.

import pandas as pd
import requests
from bs4 import BeautifulSoup

dflist = []
for i in range(1,4):
    s = requests.Session()
    res = requests.get(r'http://www.ironman.com/triathlon/events/americas/ironman/world-championship/results.aspx?p=' + str(i) + 'race=worldchampionship&rd=20181013&agegroup=Pro&sex=M&y=2018&ps=20#axzz5VRWzxmt3')
    soup = BeautifulSoup(res.content,'lxml')
    table = soup.find_all('table')
    dfs = pd.read_html(str(table))
    dflist.append(dfs)
    s.close()

print(dflist)  

Upvotes: 1

Views: 73

Answers (1)

jwodder
jwodder

Reputation: 57450

You left out the & after '?p=' + str(i), so your requests all have p set to ${NUMBER}race=worldchampionship, which ironman.com presumably can't make sense of and just ignores. Insert a & at the beginning of 'race=worldchampionship'.

To prevent this sort of mistake in the future, you can pass the URL's query parameters as a dict to the params keyword argument like so:

    params = {
        "p": i,
        "race": "worldchampionship",
        "rd": "20181013", 
        "agegroup": "Pro",
        "sex": "M",
        "y": "2018",
        "ps": "20",
    }

    res = requests.get(r'http://www.ironman.com/triathlon/events/americas/ironman/world-championship/results.aspx#axzz5VRWzxmt3', params=params)

Upvotes: 2

Related Questions