write a code to access this website https://www.cpubenchmark.net/ and get data on 5500gt…
- User
write a code to access this website https://www.cpubenchmark.net/ and get data on 5500gt CPU and arragne that data into xlsx file
- Assistant
write a code to access this website https://www.cpubenchmark.net/ and get data on 5500gt CPU and arragne that data into xlsx file
To access data from CPU Benchmark for a specific CPU (e.g., "5500GT CPU") and arrange it into an Excel (.xlsx) file, you can use Python along with libraries such as requests for making HTTP requests, BeautifulSoup for parsing HTML content, and pandas for handling and exporting data to Excel.
Please Note:
robots.txt file. Unauthorized scraping may violate terms and could lead to legal consequences.Selenium or Playwright instead of requests and BeautifulSoup.Below is a step-by-step guide and Python script to perform the task:
Make sure you have the necessary Python libraries installed. You can install them using pip:
pip install requests beautifulsoup4 pandas openpyxl
import requests
from bs4 import BeautifulSoup
import pandas as pd
import sys
def get_cpu_data(cpu_name):
# Base URL
base_url = 'https://www.cpubenchmark.net/'
# Search for the CPU
search_url = f"{base_url}cpu.php?cpu={cpu_name.replace(' ', '+')}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' # To mimic a real browser request
}
try:
response = requests.get(search_url, headers=headers)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Error fetching the CPU page: {e}")
sys.exit(1)
soup = BeautifulSoup(response.text, 'html.parser')
# Find the CPU entry (assuming it's the first result)
cpu_table = soup.find('table', {'class': 'cputable'})
if not cpu_table:
print("CPU data table not found on the page.")
sys.exit(1)
# Extract table headers
headers = []
for th in cpu_table.find('thead').find_all('th'):
headers.append(th.get_text(strip=True))
# Extract table rows
data = []
for tr in cpu_table.find('tbody').find_all('tr'):
row = []
for td in tr.find_all('td'):
row.append(td.get_text(strip=True))
data.append(row)
# Create DataFrame
df = pd.DataFrame(data, columns=headers)
return df
def save_to_excel(df, cpu_name):
excel_file = f"{cpu_name.replace(' ', '_')}_data.xlsx"
try:
df.to_excel(excel_file, index=False)
print(f"Data successfully saved to {excel_file}")
except Exception as e:
print(f"Error saving data to Excel: {e}")
def main():
cpu_name = "5500GT CPU" # Replace with the desired CPU name
print(f"Fetching data for {cpu_name}...")
cpu_data = get_cpu_data(cpu_name)
if cpu_data.empty:
print("No data found for the specified CPU.")
else:
save_to_excel(cpu_data, cpu_name)
if __name__ == "__main__":
main()
Import Libraries: The script imports necessary libraries for HTTP requests, HTML parsing, data manipulation, and Excel handling.
Function get_cpu_data:
+ to conform to URL encoding.BeautifulSoup to parse the HTML content.cputable which contains the CPU data.Function save_to_excel:
main Function:
cpu_name variable to the desired CPU.fetch_cpu_data.py.python fetch_cpu_data.py
5500GT_CPU_data.xlsx in the same directory.CPU Not Found: If the CPU name does not exactly match the entries on the website, the script might not find the data. Consider implementing a more robust search mechanism or prompting the user for possible matches.
Website Structure Changes: If the website updates its HTML structure, the script may need adjustments to the find methods used to locate the data.
Dynamic Content: If the data is loaded dynamically via JavaScript, consider using Selenium or other browser automation tools to render the page before scraping.
If you want to fetch data for a different CPU, simply change the cpu_name variable in the main function:
cpu_name = "Intel Core i7-9700K"
Then rerun the script.
If the website provides a search API or parameters, you can adjust the search_url accordingly. However, as of the knowledge cutoff in October 2023, CPU Benchmark does not offer a public API, so scraping is the primary method.
The provided Python script offers a straightforward way to scrape CPU data from CPU Benchmark and export it to an Excel file. Always ensure compliance with the website’s terms and handle exceptions gracefully to make the script robust and reliable.
Not yet included in a published release.