python - 从文本文件 Python 中提取 URL 和 TITLE
问题描述
我有以下方式的文本文件:
<a href="https://en.wikipedia.org/wiki/Scotland" h="ID=SERP,5161.1">Scotland - Wikipedia
<a href="https://www.visitscotland.com/" h="ID=SERP,5177.1">VisitScotland - Official Site
<a href="https://www.bbc.co.uk/news/scotland" h="ID=SERP,5191.1">BBC Scotland News - Official Site
<a href="https://www.lonelyplanet.com/scotland" h="ID=SERP,5207.1">Scotland travel - Lonely Planet
从此文本文件中,我想提取 URL,即仅像“en.wikipedia.org”、“www.bbc.co.uk”等主域到 Links.txt
并将标题即“苏格兰 - 维基百科”、“访问苏格兰 - 官方网站”等放入 Titles.txt
我是正则表达式的新手,尝试使用一些正则表达式函数来提取但没有成功。
解决方案
这里和这里的正则表达式的解释。假设您的数据存储在data.txt
:
import re
with open('data.txt', 'r', newline='') as f_in, \
open('links.txt', 'w', newline='') as links_out, \
open('titles.txt', 'w', newline='') as titles_out:
data = f_in.read()
for link in re.findall(r'(?:href=")([^"]+)', data):
links_out.write(link + '\n')
for title in re.findall(r'(?:>)(.*?)$', data, flags=re.M):
titles_out.write(title + '\n')
在titles.txt 中,您将拥有:
Scotland - Wikipedia
VisitScotland - Official Site
BBC Scotland News - Official Site
Scotland travel - Lonely Planet
在 links.txt 中,您将拥有:
https://en.wikipedia.org/wiki/Scotland
https://www.visitscotland.com/
https://www.bbc.co.uk/news/scotland
https://www.lonelyplanet.com/scotland
BeautifulSoup
注意:使用或类似的库更好地完成 HTML 文档的解析并且更健壮。
编辑:
要仅解析域,您可以使用urllib.urlparse
:
# on the top:
from urllib.parse import urlparse
for link in re.findall(r'(?:href=")([^"]+)', data):
url = urlparse(link)
links_out.write(url.scheme + '://' + url.netloc + '\n')
links.txt 将如下所示:
https://en.wikipedia.org
https://www.visitscotland.com
https://www.bbc.co.uk
https://www.lonelyplanet.com
推荐阅读
- powerbi - 使用 IF 语句计算的列或度量
- elasticsearch - ElasticSearch 中的预输入如何处理多个单词和部分文本匹配
- c# - 为空值或 Null 值格式化 JSON
- php - Doctrine 3 不创建外键 - PDOException: "Column 'tour_id' cannot be null"
- c++ - switch 语句导致发送两条消息
- excel - MS Excel对象锁定行基于与其他对象一起使用的值
- sql - 在 SQL 中忽略 CASE 中的 else
- mysql - 检查酒店预订系统的房间可用性
- java - 如何使用 GSON 解析漂亮打印的 JSON
- javascript - 无法将默认 angularjs 输入设置为空白