我如何使用Python从Flashscore中抓取足球结果

时间:2020-04-24 10:34:15

标签: python-3.x web-scraping beautifulsoup python-requests

网络抓取Python

'我是新手。我想抓取英超联赛2018-19赛季的成绩(赛程,成绩,日期),但是我一直在努力浏览网站。我所得到的只是空列表/ [无]。如果您有可以共享的解决方案,那将是很大的帮助。 '

“这就是我尝试过的。”

'''

import pandas as pd
import requests as uReq
from bs4 import BeautifulSoup

url = uReq.get('https://www.flashscore.com/football/england/premier-league-2018-2019/results/')

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

divs = soup.find_all('div', attrs={'id': 'live-table'})

Home = []
for div in divs:
    anchor = div.find(class_='event__participant event__participant--home')
    
    Home.append(anchor)
    
    print(Home)

'''

1 个答案:

答案 0 :(得分:5)

您必须为我的解决方案安装requests_html

这就是我要做的事情:

from requests_html import AsyncHTMLSession
from collections import defaultdict
import pandas as pd 


url = 'https://www.flashscore.com/football/england/premier-league-2018-2019/results/'

asession = AsyncHTMLSession()

async def get_scores():
    r = await asession.get(url)
    await r.html.arender()
    return r

results = asession.run(get_scores)
results = results[0]

times = results.html.find("div.event__time")
home_teams = results.html.find("div.event__participant.event__participant--home") 
scores = results.html.find("div.event__scores.fontBold")
away_teams = results.html.find("div.event__participant.event__participant--away")
event_part = results.html.find("div.event__part")


dict_res = defaultdict(list)

for ind in range(len(times)):
    dict_res['times'].append(times[ind].text)
    dict_res['home_teams'].append(home_teams[ind].text)
    dict_res['scores'].append(scores[ind].text)
    dict_res['away_teams'].append(away_teams[ind].text)
    dict_res['event_part'].append(event_part[ind].text)

df_res = pd.DataFrame(dict_res)

这将产生以下输出:

enter image description here