To extract specific information from HTML using regex (as outlined in your JSON), you can adapt your existing fetch_and_extract function to handle the scraping based on the defined patterns. Since the data structure contains specific HTML snippets and patterns, we will need to formulate a regex pattern that can parse dates from that HTML.
Given your JSON structure, it looks like you want to extract the opening date from the postDatePattern, while the strip field is presumably to assist in identifying the structure but doesn't directly relate to the extraction.
Example Implementation
Here's how you could implement the extraction for the "Government" section in your web scraping script. We'll focus on the postDatePattern.
Updated Code for Specific Extraction
We'll modify the fetch_and_extract function to incorporate this logic:
import pandas as pd
import requests
from bs4 import BeautifulSoup
import csv
import re
import json
# Step 1: Read URLs from an Excel file
def read_urls_from_excel(file_path, sheet_name, column_name):
df = pd.read_excel(file_path, sheet_name=sheet_name)
return df[column_name].dropna().tolist() # Drop NaN values and return a list of URLs
# Step 2: Fetch the web page and extract specific information
def fetch_and_extract(url, extraction_rules):
"""Fetch the webpage and extract information based on given extraction rules."""
try:
response = requests.get(url)
response.raise_for_status() # Raise an error for bad responses
soup = BeautifulSoup(response.text, 'html.parser')
results = {}
# Extract opening date using regex from the postDatePattern
post_date_pattern = extraction_rules['postDatePattern']
date_regex = r'<div class="span8">\s*<p>(.*?)<\/p>\s*<\/div>'
# Apply regex to the HTML content
match = re.search(date_regex, post_date_pattern, re.DOTALL)
results['opening_date'] = match.group(1).strip() if match else 'N/A'
return {'url': url, **results}
except Exception as e:
print(f"Error fetching {url}: {e}")
return None
# Step 3: Save the collected data to a CSV file
def save_to_csv(data, output_file):
"""Save a list of dictionaries to a CSV file."""
if data:
with open(output_file, mode='w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=data[0].keys())
writer.writeheader()
for row in data:
writer.writerow(row)
def main():
# Adjust these parameters as needed
excel_file_path = 'your_excel_file.xlsx'
sheet_name = 'Sheet1' # Adjust based on your file
column_name = 'URLs' # Adjust based on your file
output_csv_file = 'output_data.csv'
# Define your extraction rules as needed
extraction_rules = {
"postDatePattern": "<div class=\"span4\">\n <div class=\" term-description\">Opening Date</div>\n </div>\n <div class=\"span8\">\n <p>01/16/2024</p>\n </div>",
"strip": "<div class=\"span4\">\n <div class=\" term-description\">Opening Date</div>\n </div>\n <div class=\"span8\">\n <p></p>\n </div>",
}
# Step 1: Read URLs
urls = read_urls_from_excel(excel_file_path, sheet_name, column_name)
# Step 2: Collect data
collected_data = []
for url in urls:
data = fetch_and_extract(url, extraction_rules)
if data:
collected_data.append(data)
# Step 3: Save to CSV
save_to_csv(collected_data, output_csv_file)
print(f"Data saved to {output_csv_file}")
if __name__ == '__main__':
main()
Explanation of the Changes
-
Extraction Rules Parameter: The fetch_and_extract function now accepts extraction_rules as an argument, containing the JSON-like structure for extraction patterns.
-
Regex for Opening Date: The regex date_regex is crafted to match the structure of your provided postDatePattern. It looks for a p tag nested within the specified div structure to capture the date.
-
N/A Handling: If no match is found, the function assigns 'N/A' to the opening_date.
Next Steps
- Adaptation: You will need to modify the regex pattern and extraction logic whenever your data structure changes. The JSON-like configuration can be expanded to include more fields and patterns.
- Multiple Pages: If you are scraping different pages with different structures, you may consider building a system where each page type has its specific extraction rules and regex patterns, making this framework scalable and adaptable.
Feel free to share additional JSON snippets or patterns if you have more pages, and I can assist you in creating or modifying regex patterns accordingly!