如何用Beautiful Soup提取链接的最后修改日期
Solution to Extract Last Modified Data into a Dictionary
Let's break this down step by step to build the dictionary you want, mapping version numbers to their last modified timestamps:
- First, target the correct
<pre>tag: as you noted, the first<pre>is just the header (Name Last modified Size), so we'll focus on the second one (index1when usingfindAll). - Extract the raw text from that tag, then split it into individual lines. We can ignore the
../line since it's just the parent directory link. - For each valid line (like
0.1.0/ 21-Oct-2020 14:06 -), parse the key parts:- The version number is the first part, stripped of the trailing
/ - The timestamp is the combination of the next two parts (date + time)
- The version number is the first part, stripped of the trailing
- Finally, assemble these parsed values into your target dictionary.
Full Code Example
from bs4 import BeautifulSoup import requests url = "your-target-url-here" soup = BeautifulSoup(requests.get(url).content, "html.parser") # Extract text from the second pre tag and clean up lines pre_text = soup.findAll("pre")[1].get_text() lines = [line.strip() for line in pre_text.splitlines() if line.strip() and not line.startswith("../")] version_timestamp_dict = {} for line in lines: # Split line into components, then extract version and timestamp parts = line.split() version = parts[0].rstrip("/") timestamp = f"{parts[1]} {parts[2]}" version_timestamp_dict[version] = timestamp print(version_timestamp_dict) # Output: {'0.1.0': '21-Oct-2020 14:06'}
Key Details
- We clean up the raw text by stripping whitespace from each line and filtering out empty lines and the parent directory link.
- Using
rstrip("/")removes the trailing slash from the directory name to get your desired key format (0.1.0instead of0.1.0/). - Combining the second and third split parts gives us the full timestamp string you need.
内容的提问来源于stack exchange,提问作者rchitect-of-info
相关产品推荐
相关产品推荐

