首页 > 解决方案 > 从文本文件 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

我是正则表达式的新手,尝试使用一些正则表达式函数来提取但没有成功。

标签: pythonregex

解决方案


这里这里的正则表达式的解释。假设您的数据存储在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

推荐阅读