使用Requests爬取Oddsportal实时页面时获取实时赔率成功但无法获取实时比分的技术求助
Hey there! Let's fix that missing live score issue you're having. You're already hitting the right endpoint for live data—you just need to dig a little deeper into the response instead of only grabbing the table HTML.
The Problem with Your Current Approach
The feed URL you're using (https://fb.oddsportal.com/feed/livegames/live/1/0.dat?_{int(time.time() * 1000)}) doesn't just return table HTML—it wraps a full JSON object with all match metadata (including scores) in a JavaScript function call. Your regex is only pulling out the odds table, which doesn't include the score display.
Modified Code to Grab Scores + Odds
Here's how you can parse the full JSON data to get both scores and odds:
import requests, time, json from bs4 import BeautifulSoup url = f"https://fb.oddsportal.com/feed/livegames/live/1/0.dat?_{int(time.time() * 1000)}" headers = { 'User-Agent': 'curl/7.64.0', 'Referer': 'https://www.oddsportal.com/inplay-odds/live-now/soccer/' } r = requests.get(url, headers=headers) # Clean the response to convert it into valid JSON raw_json = r.text.strip().removeprefix('loadLiveGames(').removesuffix(');') live_matches = json.loads(raw_json) # Loop through each live match to extract data for match in live_matches['d']: # Core match details home_team = match['h'] away_team = match['a'] # Handle live score score_data = match.get('sc', 'Not started') if isinstance(score_data, list): live_score = f"{score_data[0]}-{score_data[1]}" else: live_score = score_data # Optional: Get match status/time match_status = match.get('st', 'Unknown') match_time = match.get('t', '') if match_time: match_status += f" ({match_time}')" print(f"{home_team} vs {away_team} | {live_score} | {match_status}") # If you still need to extract odds, parse the match's HTML match_html = match.get('html', '') if match_html: cleaned_html = match_html.replace("\\", "") soup = BeautifulSoup(cleaned_html, 'html.parser') # Extract odds from the soup here (same as your original logic)
Key Details About the Data Structure
- The
sckey in each match object holds the score: it’s either a list like[1, 0](home-away) or a string (e.g., "HT" for half-time, "FT" for full-time). - Use
stto get match status (live, half-time, etc.) andtfor elapsed minutes if the match is in play. - The
htmlfield contains the odds table you were originally extracting—you can still parse that for odds data.
A quick heads-up: Oddsportal may adjust their API structure periodically, so you might need to tweak the key names if they update the feed. But this should work for the current setup!
内容的提问来源于stack exchange,提问作者Khaled Koubaa

