Okay, here's a Python script using requests, BeautifulSoup4, and pandas to scrape the match data from the provided VLR.gg event page.
Important Notes:
Web Scraping Ethics & Terms of Service: Always check VLR.gg's robots.txt (usually at https://www.vlr.gg/robots.txt) and their Terms of Service before scraping. Scraping too aggressively can overload their servers and might be against their rules. This script includes a small delay (time.sleep) between requests to be polite.
Website Structure Changes: Web scraping scripts are fragile. If VLR.gg changes the HTML structure of their website, this script might break and will need adjustments.
Dependencies: You need to install the required libraries:
bash
pip install requests beautifulsoup4 pandas lxml
(lxml is a recommended parser for BeautifulSoup)
The Python Script:
python
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
import re # Using regex to extract match ID
def scrape_vlr_event(event_url, num_matches=30):
"""
Scrapes match data from a VLR.gg event matches page.
Args:
event_url (str): The URL of the VLR.gg event matches page.
num_matches (int): The maximum number of matches to scrape.
Returns:
pandas.DataFrame: A DataFrame containing the scraped match data,
or None if an error occurs.
"""
base_url = "https://www.vlr.gg"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Referer': 'https://www.vlr.gg/'
}
match_data_list = []
print(f"Fetching event page: {event_url}")
try:
response = requests.get(event_url, headers=headers, timeout=15)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
except requests.exceptions.RequestException as e:
print(f"Error fetching event page: {e}")
return None
soup = BeautifulSoup(response.text, 'lxml')
# Find all match item containers (adjust selector if needed)
# The matches are usually within <a> tags with class 'match-item'
match_items = soup.find_all('a', class_='match-item', href=True)
if not match_items:
print("No match items found on the event page. Check the URL or page structure.")
return None
print(f"Found {len(match_items)} potential matches on the page. Processing up to {num_matches}...")
processed_count = 0
for item in match_items:
if processed_count >= num_matches:
break
match_rel_url = item['href']
match_page_url = base_url + match_rel_url
# --- Extract basic info available on the list page ---
match_id = None
match_id_search = re.search(r'/(\d+)/', match_rel_url)
if match_id_search:
match_id = match_id_search.group(1)
else:
print(f"Warning: Could not extract match ID from {match_rel_url}")
continue # Skip if no ID
date_div = item.find('div', class_='match-item-date')
match_date = date_div.get_text(strip=True) if date_div else 'N/A'
# Team names can be tricky, look for specific structure
teams = item.find_all('div', class_='match-item-vs-team-name')
team1_name = teams[0].get_text(strip=True) if len(teams) > 0 else 'N/A'
team2_name = teams[1].get_text(strip=True) if len(teams) > 1 else 'N/A'
# Overall scores to determine winner (might need adjustment)
scores = item.find_all('div', class_='match-item-vs-team-score')
score1_str = scores[0].get_text(strip=True) if len(scores) > 0 else '0'
score2_str = scores[1].get_text(strip=True) if len(scores) > 1 else '0'
try:
score1 = int(score1_str)
score2 = int(score2_str)
if score1 > score2:
match_winner = team1_name
elif score2 > score1:
match_winner = team2_name
else: # Handle draws or TBD scores if necessary
match_winner = 'TBD/Draw'
except ValueError:
match_winner = 'N/A' # If scores aren't integers
print(f"\nProcessing Match ID: {match_id} ({team1_name} vs {team2_name})")
print(f" -> Fetching match details: {match_page_url}")
# --- Navigate to the individual match page for map details ---
# Add a delay to be polite to the server
time.sleep(1.5) # Wait 1.5 seconds before the next request
try:
match_response = requests.get(match_page_url, headers=headers, timeout=15)
match_response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Error fetching match page {match_page_url}: {e}")
# Add basic info even if map details fail
match_data = {
'match_id': match_id,
'date': match_date,
'team1': team1_name,
'team2': team2_name,
'map1': 'N/A',
'map1_score': 'N/A',
'map2': 'N/A',
'map2_score': 'N/A',
'map3': 'N/A',
'map3_score': 'N/A',
'match_winner': match_winner
}
match_data_list.append(match_data)
processed_count += 1
continue # Go to the next match
match_soup = BeautifulSoup(match_response.text, 'lxml')
# Initialize map data
map_details = {
'map1': None, 'map1_score': None,
'map2': None, 'map2_score': None,
'map3': None, 'map3_score': None,
}
# Find map stats containers (Selector might need adjustment)
# Often within a 'vm-stats-container', then 'vm-stats-game' for each map
game_sections = match_soup.find_all('div', class_='vm-stats-game')
for i, game in enumerate(game_sections):
if i >= 3: # We only care about up to 3 maps
break
map_name_div = game.find('div', class_='map')
map_name = map_name_div.find('span', style=lambda value: value and 'position: relative;' in value).get_text(strip=True) if map_name_div else 'Map N/A'
# Alternative map name finding if the above fails:
# map_name_div = game.find('div', class_=re.compile(r"map-name-map-\w+"))
# map_name = map_name_div.get_text(strip=True) if map_name_div else 'Map N/A'
# Find scores for this map (structure can vary)
scores_divs = game.find_all('div', class_='score') # Often 2 score divs per map
map_score = 'N/A'
if len(scores_divs) == 2:
score_t1 = scores_divs[0].get_text(strip=True)
score_t2 = scores_divs[1].get_text(strip=True)
map_score = f"{score_t1}-{score_t2}"
# Assign to the correct map slot
map_key = f'map{i+1}'
score_key = f'map{i+1}_score'
map_details[map_key] = map_name
map_details[score_key] = map_score
# Combine all data for this match
match_data = {
'match_id': match_id,
'date': match_date,
'team1': team1_name,
'team2': team2_name,
'map1': map_details['map1'],
'map1_score': map_details['map1_score'],
'map2': map_details['map2'],
'map2_score': map_details['map2_score'],
'map3': map_details['map3'],
'map3_score': map_details['map3_score'],
'match_winner': match_winner
}
match_data_list.append(match_data)
processed_count += 1
print(f" -> Successfully processed Match ID: {match_id}")
if not match_data_list:
print("No matches were successfully processed.")
return None
# Create DataFrame
df = pd.DataFrame(match_data_list)
# Fill potential missing map data with 'N/A' for consistency
df.fillna('N/A', inplace=True)
return df
# --- Main Execution ---
if __name__ == "__main__":
# The URL provided in the prompt
vlr_event_url = "https://www.vlr.gg/event/matches/2347/champions-tour-2025-americas-stage-1/?series_id=4541"
number_of_matches_to_scrape = 30
match_df = scrape_vlr_event(vlr_event_url, number_of_matches_to_scrape)
if match_df is not None:
print("\n--- Scraping Complete ---")
print(f"Successfully created DataFrame with {len(match_df)} rows.")
# Display the first few rows and info
print("\nDataFrame Head:")
print(match_df.head())
print("\nDataFrame Info:")
match_df.info()
# Optional: Save to CSV
try:
output_filename = "vlr_americas_stage1_matches.csv"
match_df.to_csv(output_filename, index=False, encoding='utf-8')
print(f"\nDataFrame saved to {output_filename}")
except Exception as e:
print(f"\nError saving DataFrame to CSV: {e}")
else:
print("\n--- Scraping Failed ---")
print("Could not create DataFrame.")
Explanation:
Import Libraries: Imports requests (for HTTP requests), BeautifulSoup (for HTML parsing), pandas (for DataFrame), time (for delays), and re (for regular expressions to extract the match ID).
scrape_vlr_event Function:
Takes the event_url and num_matches as input.
Sets up base_url and headers (including User-Agent is important).
Initializes an empty list match_data_list to store data for each match.
Fetches Event Page: Makes a requests.get call to the main event URL. Includes error handling (try-except) and checks the response status.
Parses Event Page: Uses BeautifulSoup to parse the HTML.
Finds Match Items: Locates all the match links (usually <a> tags with class match-item). If none are found, it exits.
Iterates Through Matches: Loops through the found match_items, limited by num_matches.
Extracts List Page Data: For each item, it extracts the relative match URL, constructs the full URL, extracts the match_id using regex, finds the date, team names, and overall scores (used to determine the match_winner). Basic error checks are included (e.g., checking if elements exist).
Navigates to Match Page: Prints progress and makes another requests.get call to the individual match page URL. Crucially, it includes a time.sleep(1.5) before this request to avoid hitting the server too rapidly. Includes error handling for this request.
Parses Match Page: Creates a newBeautifulSoup object for the individual match page's HTML.
Extracts Map Data:
Initializes a dictionary map_details to store map names and scores.
Finds the sections containing data for each map (the selector div.vm-stats-game is common, but inspect the specific match page HTML if this doesn't work).
Iterates through the found map sections (max 3).
Inside each section, it tries to find the map name (often within a with class and then a specific ) and the scores (often two s with class ). The exact selectors might need adjustment based on VLR's current structure.
Remember to run pip install requests beautifulsoup4 pandas lxml before executing the script.
Assigns the found map name and score (formatted like "13-5") to the correct map_details keys (map1, map1_score, etc.).
Appends Data: Creates a dictionary match_data containing all the extracted information for the current match and appends it to match_data_list.
Increments Counter: Keeps track of processed matches.
Creates DataFrame: After the loop, converts the match_data_list into a Pandas DataFrame.
Fills NA: Uses df.fillna('N/A', inplace=True) to replace any None values (which occur if map data wasn't found or a map wasn't played) with the string 'N/A'.
Returns the DataFrame.
Main Execution (if __name__ == "__main__":)
Sets the target vlr_event_url and the desired number_of_matches_to_scrape.
Calls the scrape_vlr_event function.
If the function returns a DataFrame successfully, it prints the head and info, and optionally saves it to a CSV file named vlr_americas_stage1_matches.csv.
If the function fails (returns None), it prints an error message.