Certainly! Below is a Python script using BeautifulSoup to parse the HTML document you provided. The script extracts the necessary data and formats it into a CSV-like structure.
from bs4 import BeautifulSoup
# Sample HTML content
html_content = """
<html lang="en">
<head></head>
<body class="navia ">
<!-- Wraps all page content -->
<div id="wrap">
<input class="js-tvsearch" type="hidden" value='{"ands":[],"minday":"06/04/2009","maxday":"09/04/2024"}'/>
<!-- Begin page content -->
<main id="maincontent">
<div class="container container-ia">
<table class="archext">
<caption>CAPTION_TITLE</caption>
<tr><th>file<th>as jpg<th>timestamp<th>size</tr>
<tr><td><a href="LINK_URL_A">ENTRY_NAME_A</a><td><td>1996-12-24 23:32<td id="size">359676</tr>
<tr><td><a href="LINK_URL_B">ENTRY_NAME_B</a></a><td><td>1996-12-24 23:32<td id="size">1428988</tr>
<tr><td><a href="LINK_URL_C">ENTRY_NAME_C</a><td><td>1996-12-24 23:32<td id="size">908284</tr>
<tr><td><a href="LINK_URL_ZZZ">ENTRY_NAME_ZZZ</a><td><td>1996-12-24 23:32<td id="size">908284</tr>
</table>
</div><!--/.container-->
</main>
</div><!--/#wrap-->
</body>
</html>
"""
# Parse the HTML content
soup = BeautifulSoup(html_content, 'html.parser')
# Extract caption title
caption_title = soup.find('caption').text.strip()
# Extract each entry row data
table = soup.find('table', class_='archext')
rows = table.find_all('tr')[1:] # Skip the header row
# Prepare CSV-like output
output = []
for row in rows:
cols = row.find_all('td')
entry_name = cols[0].find('a').text.strip()
link_url = cols[0].find('a')['href'].strip()
output.append(f"{entry_name},{link_url},{caption_title}")
# Print the output in CSV-like format
for line in output:
print(line)
How It Works
-
Parse HTML: The script uses BeautifulSoup to parse the given HTML content.
-
Extract Caption Title: It finds the <caption> tag and extracts its text, which is the CAPTION_TITLE.
-
Iterate Through Rows: It iterates through each <tr> in the table (skipping the header) and extracts the ENTRY_NAME and LINK_URL from the <a> tags.
-
Format Output: It formats the extracted data into the desired CSV-like structure and prints it.
Usage
Replace html_content with your actual HTML content or load it from a file. The script will then parse it and output the data in the format you provided.
This script assumes the HTML content structure you've shared remains consistent. Adjustments may be necessary if there are variations in real documents.
ENTRY_NAME_A,LINK_URL_A,PATH_1,FOLDER,CAPTION_TITLE
ENTRY_NAME_B,LINK_URL_B,PATH_1,FOLDER,CAPTION_TITLE
ENTRY_NAME_C,LINK_URL_C,PATH_2,FOLDER,CAPTION_TITLE
ENTRY_NAME_D,LINK_URL_D,PATH_2,FOLDER,CAPTION_TITLE
ENTRY_NAME_E,LINK_URL_E,PATH_3,FOLDER,CAPTION_TITLE
ENTRY_NAME_F,LINK_URL_F,PATH_3,FOLDER,CAPTION_TITLE
ENTRY_NAME_G,LINK_URL_G,PATH_3,FOLDER,CAPTION_TITLE
...
ENTRY_NAME_ZZZ,LINK_URL_ZZZ,PATH_2049,FOLDER,CAPTION_TITLE
To handle HTML tables with potentially nested folder paths while maintaining generality, we can enhance the BeautifulSoup parser to recognize path structures and associate them with individual entries. Below is the revised code:
from bs4 import BeautifulSoup
# Sample HTML content
html_content = """
<html lang="en">
<head></head>
<body class="navia ">
<div id="wrap">
<main id="maincontent">
<div class="container container-ia">
<table class="archext">
<caption>CAPTION_TITLE</caption>
<tr><th>file<th>as jpg<th>timestamp<th>size</tr>
<tr><td>FOLDER/<td><td>2017-11-18 08:40<td id="size"></tr>
<tr><td>FOLDER/PATH_1/<td><td>2017-11-18 08:40<td id="size"></tr>
<tr><td><a href="LINK_URL_A">ENTRY_A</a><td><td>2017-11-13 17:41<td id="size">679888</tr>
<tr><td><a href="LINK_URL_B">ENTRY_B</a><td><td>2017-11-13 17:41<td id="size">643252</tr>
<tr><td>FOLDER/PATH_2/<td><td>2017-11-18 08:40<td id="size"></tr>
<tr><td><a href="LINK_URL_C">ENTRY_C</a><td><td>2017-11-16 17:37<td id="size">710795</tr>
<tr><td><a href="LINK_URL_D">ENTRY_D</a><td><td>2017-11-16 17:37<td id="size">745957</tr>
<tr><td>FOLDER/PATH_3<td><td>2017-11-18 08:40<td id="size"></tr>
<tr><td><a href="LINK_URL_E">ENTRY_E</a><td><td>2017-11-13 17:41<td id="size">1323204</tr>
<tr><td><a href="LINK_URL_F">ENTRY_F</a><td><td>2017-11-13 17:41<td id="size">1268080</tr>
<tr><td><a href="LINK_URL_G">ENTRY_G</a><td><td>2017-11-13 17:41<td id="size">12000225</tr>
<tr><td>FOLDER/PATH_4<td><td>2017-11-18 08:40<td id="size"></tr>
<tr><td>Hard/Hard-sha no Shachou ga/<td><td>2017-11-18 08:40<td id="size"></tr>
</table>
</div>
</main>
</div>
</body>
</html>
"""
# Parse the HTML content
soup = BeautifulSoup(html_content, 'html.parser')
# Extract caption title
caption_title = soup.find('caption').text.strip()
# Extract each entry row data
table = soup.find('table', class_='archext')
rows = table.find_all('tr')[1:] # Skip the header row
# Initialize path tracking variables
current_folder = None
current_subpath = None
# Prepare CSV-like output
output = []
for row in rows:
cols = row.find_all('td')
if cols[0].find('a'):
# It's a file entry
entry_name = cols[0].find('a').text.strip()
link_url = cols[0].find('a')['href'].strip()
if current_folder and current_subpath:
output.append(f"{entry_name},{link_url},{current_subpath},{current_folder},{caption_title}")
elif current_folder:
output.append(f"{entry_name},{link_url},,{current_folder},{caption_title}")
else:
# It's a path entry
path = cols[0].text.strip().rstrip('/')
parts = path.split('/')
if len(parts) == 2:
current_folder = parts[0]
current_subpath = parts[1]
elif len(parts) == 1:
current_folder = parts[0]
current_subpath = None
# Print the output in CSV-like format
for line in output:
print(line)
Explanation
-
Tracking Folders and Paths: The script checks if the <td> element contains an <a> tag to differentiate file entries from path entries.
-
Path Management:
- If a
<td> without an <a> contains a full path (e.g., FOLDER/PATH_1/), it updates both current_folder and current_subpath.
- If it's a base folder path only (e.g.,
FOLDER/), it sets current_folder and clears current_subpath.
-
Formatting Output: Concatenates the path and folder information with entry details and caption for CSV-like output.
This code is now more generic, allowing it to handle folders and subpaths and assume correct path hierarchies based on the table's structure. Adjustments may be further needed if folder and file structures become more complex.
To extend the script to fetch and parse HTML content from a given URL using the requests module, follow these steps. Here is the relevant part of the script:
import requests
from bs4 import BeautifulSoup
# Function to fetch HTML from a given URL
def fetch_html(url):
try:
response = requests.get(url)
response.raise_for_status() # Check for HTTP errors
return response.text # Return the content of the response as a string
except requests.exceptions.RequestException as e:
print(f"Error fetching URL {url}: {e}")
return None
def parse_html_content(html_content):
if html_content is None:
return []
# Parse the HTML content
soup = BeautifulSoup(html_content, 'html.parser')
# Extract caption title
caption_title = soup.find('caption').text.strip()
# Extract each entry row data
table = soup.find('table', class_='archext')
rows = table.find_all('tr')[1:] # Skip the header row
# Initialize path tracking variables
current_folder = None
current_subpath = None
# Prepare CSV-like output
output = []
for row in rows:
cols = row.find_all('td')
if cols[0].find('a'):
# It's a file entry
entry_name = cols[0].find('a').text.strip()
link_url = cols[0].find('a')['href'].strip()
if current_folder and current_subpath:
output.append(f"{entry_name},{link_url},{current_subpath},{current_folder},{caption_title}")
elif current_folder:
output.append(f"{entry_name},{link_url},,{current_folder},{caption_title}")
else:
# It's a path entry
path = cols[0].text.strip().rstrip('/')
parts = path.split('/')
if len(parts) == 2:
current_folder = parts[0]
current_subpath = parts[1]
elif len(parts) == 1:
current_folder = parts[0]
current_subpath = None
return output
# Example URL
url = "http://example.com/path-to-html-page"
# Fetch HTML content from URL
html_content = fetch_html(url)
# Parse and extract data
parsed_data = parse_html_content(html_content)
# Output parsed data in CSV-like format
for line in parsed_data:
print(line)
Explanation
-
Fetching HTML:
- The
fetch_html function uses the requests.get method to retrieve the webpage content from the specified URL.
response.raise_for_status() is used to raise an error if the HTTP request returned an unsuccessful status code.
- If successful, the full HTML content as a string is returned.
-
Parsing HTML:
parse_html_content function takes the HTML as input and processes it using BeautifulSoup.
- The same path and entry extraction logic is used.
-
Putting It Together:
- You first call
fetch_html with the desired URL.
- Pass the fetched HTML to
parse_html_content.
- The parsed data is printed in the desired CSV-like format.
Ensure that the requests and beautifulsoup4 packages are installed in your Python environment using pip install requests beautifulsoup4. Adjust the url variable with the actual URL you wish to parse.
import requests
from time import sleep
# Assuming fetch_html is defined elsewhere
def parse_ia_archive(filename, output, ia_id):
with open(output, 'w') as outfile:
with open(filename, 'r') as file:
for entry in file:
entry = entry.strip() # Removes leading/trailing whitespace, including newlines
url = std_url + ia_id + entry
print(url)
sleep(5)
# Fetch HTML content from URL
html_content = fetch_html(url)
# Parse and extract data
parsed_data = parse_html_content(html_content)
# Output parsed data in CSV-like format
for line in parsed_data:
print(line, file=outfile)
# Define your std_url, ia_id, fetch_html, and parse_html_content as needed