I am working on the following codes to scrape a dynamic content website. I have been helped to improve my code to scrape one page of the content. Now, I would like to add a FOR loop to scrape multiple pages and add the related name as a new column to distinguish each page.
Id | Name |
---|---|
HK_2019_D105 | Name1 |
HK_2018_C509 | Name2 |
The output is combined all pages into one dataframe. Please suggest how to improve the following code.
import pandas as pd
import requests
Id = df['Id']
cookies = {
'BotMitigationCookie_9518109003995423458': '343775001600940465b2KTzJpwY5pXpiVNIRRi97Z3ELk='
}
for j in Id:
def main(url):
r = requests.post(url, cookies=cookies)
df = pd.read_html(r.content, header=0, attrs={'class':'table_bd f_tal f_fs13'})
new = pd.concat(df, ignore_index=True)
data = pd.DataFrame(new, columns=['Date','Type','Racecourse/Track','Workouts','Gear'])
data.to_csv('data'+str(j)+'.csv')
main('https://racing.hkjc.com/racing/information/English/Trackwork/TrackworkResult.aspx?HorseId='+str(j)+'')
Output:
header1 | header2 | Name |
---|---|---|
First | row | Name1 |
Second | row | Name1 |
First | row | Name2 |
Second | row | Name2 |
Assuming you are trying to combine each request into a single CSV file, you can use the .append()
function. The Id
and Name
columns can be added before doing the append:
import pandas as pd
import requests
df_ids = pd.read_csv('ids.csv')
cookies = {'BotMitigationCookie_9518109003995423458': '343775001600940465b2KTzJpwY5pXpiVNIRRi97Z3ELk='}
df_output = pd.DataFrame(columns=['Date', 'Type', 'Racecourse/Track', 'Workouts', 'Gear', 'Id', 'Name'])
for id, name in df_ids.itertuples(index=False):
print(f'Getting: {id} for {name}')
url = f'https://racing.hkjc.com/racing/information/English/Trackwork/TrackworkResult.aspx?HorseId={id}'
r = requests.post(url, cookies=cookies)
df = pd.read_html(r.content, header=0, attrs={'class':'table_bd f_tal f_fs13'})[0]
df['Id'] = id
df["Name"] = name
df_output = df_output.append(df, ignore_index=True)
df_output.to_csv('output.csv', index=False)
Giving you an output.csv
file starting:
Date,Type,Racecourse/Track,Workouts,Gear,Id,Name
10/02/2021,Trotting,Sha Tin SmT,SmT 1 Round - Fast (R.B.),H,HK_2019_D105,Name1
09/02/2021,Swimming,Sha Tin,,,HK_2019_D105,Name1
09/02/2021,Trotting,Sha Tin SmT,SmT 1 Round - Fast (R.B.),H,HK_2019_D105,Name1
08/02/2021,Swimming,Sha Tin,,,HK_2019_D105,Name1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.