BASH技术问题:从URL提取指定标签间年份并本地存储
实现思路与具体方案
Python 脚本实现(批量处理首选)
这种方案灵活性强,能精准定位目标标签,且全程在内存中处理网页内容,不会保存完整网页到本地。
- 所需依赖:
requests(用于发起网页请求)、beautifulsoup4(用于解析HTML) - 安装依赖:
pip install requests beautifulsoup4
- 示例代码:
import requests from bs4 import BeautifulSoup # 待处理的URL列表 url_list = [ "https://example.com/page1", "https://example.com/page2", # 可继续添加更多URL ] # 存储年份的本地文件 output_file = "extracted_years.txt" # 初始化输出文件(清空已有内容) with open(output_file, "w", encoding="utf-8") as f: pass for url in url_list: try: # 发起请求,仅在内存中获取网页内容 response = requests.get(url, timeout=10) response.raise_for_status() # 捕获请求失败的情况 # 解析HTML内容 soup = BeautifulSoup(response.text, "html.parser") # 定位目标<td>标签:匹配class为text且style包含border-right:0的元素 target_td = soup.find("td", class_="text", style=lambda s: s and "border-right:0" in s) if target_td: # 提取并清洗年份文本(去除换行、空格) year = target_td.get_text(strip=True) # 可选:校验是否为4位有效年份 if year.isdigit() and len(year) == 4: # 将年份追加写入本地文件 with open(output_file, "a", encoding="utf-8") as f: f.write(f"{year}\n") print(f"从{url}提取到年份:{year}") else: print(f"{url}提取内容非有效年份:{year}") else: print(f"{url}未找到目标<td>标签") except Exception as e: print(f"处理{url}出错:{str(e)}")
- 核心特点:
- 全程仅在内存中处理网页,不生成完整网页的本地文件
- 包含异常处理和年份有效性校验,避免无效数据混入
- 支持批量处理任意数量的URL
命令行工具组合(快速处理少量URL)
无需编写脚本,用curl和grep的组合即可完成提取,适合临时需求。
- 单URL处理命令:
curl -s "https://example.com/page1" | grep -o '<td class="text" style="border-right:0;">\s*\d{4}\s*</td>' | grep -o '\d{4}' >> extracted_years.txt
- 批量处理(先将所有URL写入
urls.txt,每行一个):
while read url; do curl -s "$url" | grep -o '<td class="text" style="border-right:0;">\s*\d{4}\s*</td>' | grep -o '\d{4}' >> extracted_years.txt done < urls.txt
- 核心特点:
curl -s静默请求网页,内容仅输出到控制台,不保存本地- 两次
grep分别完成标签匹配和年份提取,直接将结果写入文件
内容的提问来源于stack exchange,提问作者StOMicha
相关产品推荐
相关产品推荐

