|
| 1 | +import requests |
| 2 | +from bs4 import BeautifulSoup |
| 3 | +import pandas as pd |
| 4 | +import json |
| 5 | +from urllib.parse import urljoin |
| 6 | + |
| 7 | +# Function to check robots.txt for scraping permission |
| 8 | +def check_robots_txt(base_url): |
| 9 | + robots_url = urljoin(base_url, '/robots.txt') |
| 10 | + response = requests.get(robots_url) |
| 11 | + if response.status_code == 200: |
| 12 | + robots_txt = response.text |
| 13 | + if "Disallow: /" in robots_txt: |
| 14 | + return False |
| 15 | + return True |
| 16 | + return False |
| 17 | + |
| 18 | +# Function to list all tables in the HTML |
| 19 | +def list_tables(soup): |
| 20 | + tables = soup.find_all("table") |
| 21 | + if not tables: |
| 22 | + raise Exception("No tables found on the webpage.") |
| 23 | + table_summaries = [] |
| 24 | + for i, table in enumerate(tables): |
| 25 | + summary = table.attrs.get("summary", f"Table {i+1}") |
| 26 | + table_summaries.append(summary) |
| 27 | + return tables, table_summaries |
| 28 | + |
| 29 | +# Function to extract data from the selected table |
| 30 | +def extract_data(table): |
| 31 | + data = [] |
| 32 | + headers = [header.text.strip() for header in table.find_all("th")] |
| 33 | + rows = table.find_all("tr")[1:] # Skipping the header row |
| 34 | + for row in rows: |
| 35 | + cells = row.find_all("td") |
| 36 | + row_data = [cell.text.strip() for cell in cells] |
| 37 | + data.append(row_data) |
| 38 | + return headers, data |
| 39 | + |
| 40 | +# Main function to perform web scraping |
| 41 | +def main(): |
| 42 | + # Read the URL from the user |
| 43 | + base_url = input("Enter the URL of the website to scrape: ") |
| 44 | + |
| 45 | + # Check if scraping is allowed |
| 46 | + if not check_robots_txt(base_url): |
| 47 | + print("It is not possible to perform web scraping on this website.") |
| 48 | + return |
| 49 | + |
| 50 | + # Send a GET request to fetch the raw HTML content |
| 51 | + response = requests.get(base_url) |
| 52 | + if response.status_code != 200: |
| 53 | + raise Exception(f"Failed to load page {base_url}") |
| 54 | + |
| 55 | + # Parse the content with BeautifulSoup |
| 56 | + soup = BeautifulSoup(response.content, "html.parser") |
| 57 | + |
| 58 | + # List all tables |
| 59 | + try: |
| 60 | + tables, table_summaries = list_tables(soup) |
| 61 | + except Exception as e: |
| 62 | + print(f"Error during table listing: {e}") |
| 63 | + return |
| 64 | + |
| 65 | + # Display the tables to the user and ask for a selection |
| 66 | + print("Tables found on the webpage:") |
| 67 | + for i, summary in enumerate(table_summaries): |
| 68 | + print(f"{i + 1}: {summary}") |
| 69 | + |
| 70 | + try: |
| 71 | + table_index = int(input("Enter the number of the table you want to scrape: ")) - 1 |
| 72 | + if table_index < 0 or table_index >= len(tables): |
| 73 | + raise ValueError("Invalid table number selected.") |
| 74 | + except ValueError as e: |
| 75 | + print(f"Error during table selection: {e}") |
| 76 | + return |
| 77 | + |
| 78 | + # Extract data from the selected table |
| 79 | + try: |
| 80 | + headers, data = extract_data(tables[table_index]) |
| 81 | + except Exception as e: |
| 82 | + print(f"Error during data extraction: {e}") |
| 83 | + return |
| 84 | + |
| 85 | + # Convert to DataFrame |
| 86 | + df = pd.DataFrame(data, columns=headers) |
| 87 | + |
| 88 | + # Save to CSV |
| 89 | + df.to_csv("scraped_data.csv", index=False) |
| 90 | + |
| 91 | + # Save to JSON |
| 92 | + df.to_json("scraped_data.json", orient="records") |
| 93 | + |
| 94 | + print("Data has been scraped and saved to scraped_data.csv and scraped_data.json") |
| 95 | + |
| 96 | +if __name__ == "__main__": |
| 97 | + main() |
0 commit comments