本文目录导读:

- 使用正则表达式(Python示例)
- 批量处理文本文件(Python)
- 使用命令行工具(Linux/Mac)
- HTML内容中的链接提取
- 使用在线工具
- 高级提取(处理各种URL格式)
- 导出结果到Excel/CSV
- 注意事项
使用正则表达式(Python示例)
import re
def extract_links(text):
# HTTP/HTTPS 链接
url_pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+[^\s]*'
return re.findall(url_pattern, text)
# 示例
text = """
请访问 https://example.com 和 http://test.org/page?q=1
还有 https://www.google.com/search?q=python
"""
links = extract_links(text)
for link in links:
print(link)
批量处理文本文件(Python)
import re
import os
def batch_extract_links(folder_path):
all_links = []
for filename in os.listdir(folder_path):
if filename.endswith('.txt'):
file_path = os.path.join(folder_path, filename)
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
links = re.findall(r'https?://[^\s]+', content)
all_links.extend(links)
return all_links
# 使用
links = batch_extract_links('./text_files')
print(f"共提取 {len(links)} 个链接")
使用命令行工具(Linux/Mac)
grep提取
# 提取所有URL grep -oP 'https?://[^\s]+' file.txt # 提取并保存到新文件 grep -oP 'https?://[^\s]+' file.txt > extracted_links.txt # 批量处理多个文件 grep -r -oP 'https?://[^\s]+' ./folder/ > all_links.txt
sed + grep组合
# 更精确的URL匹配 cat text.txt | grep -oE 'https?://[A-Za-z0-9./?=_-]+' > links.txt
HTML内容中的链接提取
from bs4 import BeautifulSoup
import re
def extract_html_links(html_content):
soup = BeautifulSoup(html_content, 'html.parser')
# 提取a标签的href
links = []
for a in soup.find_all('a', href=True):
links.append(a['href'])
# 提取img标签的src
for img in soup.find_all('img', src=True):
if img['src'].startswith('http'):
links.append(img['src'])
return links
# 示例
html = """
<a href="https://example.com">链接1</a>
<img src="https://img.example.com/photo.jpg">
<a href="/relative/page">相对路径</a>
"""
links = extract_html_links(html)
print(links)
使用在线工具
- Regex101:在线测试正则表达式
- 在线链接提取器:直接粘贴文本提取
- CyberChef:可视化数据处理
高级提取(处理各种URL格式)
import re
def advanced_url_extractor(text):
# 更全面的URL模式
url_pattern = r'''
(?:(?:https?|ftp):\/\/)? # 协议
(?:www\.)? # www
[-a-zA-Z0-9@:%._\+~#=]{1,256} # 域名
\.[a-zA-Z0-9()]{1,6} # 顶级域名
\b
(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*)
'''
return re.findall(url_pattern, text, re.VERBOSE)
# 测试各种URL格式
test_text = """
https://www.example.com
http://sub.domain.com/path?param=value
https://github.com/user/repo
ftp://files.example.com/document.pdf
www.example.com (不带协议)
"""
print(advanced_url_extractor(test_text))
导出结果到Excel/CSV
import csv
import re
def extract_to_csv(text, output_file='extracted_links.csv'):
links = re.findall(r'https?://[^\s]+', text)
with open(output_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['序号', '链接'])
for i, link in enumerate(links, 1):
writer.writerow([i, link])
print(f"已导出 {len(links)} 个链接到 {output_file}")
# 使用
text = "你的文本内容..."
extract_to_csv(text)
注意事项
- 编码问题:处理中文文本时注意UTF-8编码
- 特殊字符:URL中可能包含编码后的字符
- 相对路径:HTML中的相对路径需要转换为绝对路径
- 重复链接:考虑是否需要去重处理
选择合适的工具和方法取决于你的具体需求、技术环境以及数据量大小,对于简单任务,使用正则表达式最快;对于复杂HTML解析,BeautifulSoup更合适。