如何使用 Python 正则表达式从 HTML 链接中提取 URL?

pythonserver side programmingprogramming

URL统一资源定位符 的首字母缩写;它用于识别互联网上的位置资源。例如,以下 URL 用于识别 Google 和 Microsoft 网站的位置 −

https://www.google.com
https://www.microsoft.com

URL 由域名、路径、端口号等组成。可以使用正则表达式解析和处理 URL。因此,如果我们想使用正则表达式,我们必须使用 Python 中的 re 库。

示例

以下是演示 URL − 的示例

URL:https://www.tutorialspoint.com/courses
如果我们解析上述 URL,我们可以找到网站名称和协议
主机名:tutorialspoint.com
协议:https

正则表达式

在 Python 语言中,正则表达式是用于查找匹配字符串的搜索模式之一。

Python 有四种用于正则表达式 − 的方法

  • search() − 它用于查找第一个匹配项。

  • match() −它用于仅查找相同匹配项

  • findall() − 它用于查找所有匹配项

  • sub() −它用于用新字符串替换匹配模式的字符串。

如果我们想使用 Python 语言在 URL 中搜索所需的模式,我们使用 re.findall() 函数,这是一个 re 库函数。

语法

以下是 Python 中搜索函数 re.findall 的语法或用法


re.findall(regex, string)

上述语法将字符串中所有不重叠的模式匹配作为字符串列表返回。

示例

要提取 URL,我们可以使用以下代码 −

import re
text= '<p>Hello World: </p><a href="http://tutorialspoint.com">More Courses</a><a href="https://www.tutorialspoint.com/market/index.asp">Even More Courses</a>'
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', text)
print("Original string: ",text)
print("Urls:",urls)

输出

以下是上述程序执行后的输出。

原始字符串:<p>Hello World: </p><a href="http://tutorialspoint.com">更多课程</a><a href="https://www.tutorialspoint.com/market/index.asp">更多课程</a>
Urls:['http://tutorialspoint.com', 'https://www.tutorialspoint.com/market/index.asp']

示例

以下程序演示了如何从给定的 URL 中提取主机名和协议。

import re
website = 'https://www.tutorialspoint.com/'
#查找协议
object1 = re.findall('(\w+)://', website)
print(object1)
#查找主机名
object2 = re.findall('://www.([\w\-\.]+)', website)
print(object2)

输出

以下是上述程序执行时的输出。

['https']
['tutorialspoint.com']

示例

以下程序演示了构造路径元素的通用 URL 的用法。

# 在线 Python-3 编译器(解释器)

import re

# url
url = 'http://www.tutorialspoint.com/index.html'

# 查找所有捕获组
object = re.findall('(\w+)://([\w\-\.]+)/(\w+).(\w+)', url)
print(object)

输出

以下是上述程序执行时的输出。

[('http', 'www.tutorialspoint.com', 'index', 'html')]

相关文章