如何使用 python 从字符串中提取 url? [英] How do you extract a url from a string using python?

查看:45
本文介绍了如何使用 python 从字符串中提取 url?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

string = "这是一个链接 http://www.google.com"

我如何提取http://www.google.com"?

(每个链接的格式相同,即http://")

解决方案

可能有几种方法可以做到这一点,但最干净的方法是使用正则表达式

<预><代码>>>>myString = "这是一个链接 http://www.google.com">>>print re.search("(?Phttps?://[^s]+)", myString).group("url")http://www.google.com

如果可以有多个链接,您可以使用类似于下面的内容

<预><代码>>>>myString = "这些是 http://www.google.com 和 http://stackoverflow.com/questions/839994/extracting-a-url-in-python 的链接">>>打印 re.findall(r'(https?://[^s]+)', myString)['http://www.google.com', 'http://stackoverflow.com/questions/839994/extracting-a-url-in-python']>>>

For example:

string = "This is a link http://www.google.com"

How could I extract 'http://www.google.com' ?

(Each link will be of the same format i.e 'http://')

解决方案

There may be few ways to do this but the cleanest would be to use regex

>>> myString = "This is a link http://www.google.com"
>>> print re.search("(?P<url>https?://[^s]+)", myString).group("url")
http://www.google.com

If there can be multiple links you can use something similar to below

>>> myString = "These are the links http://www.google.com  and http://stackoverflow.com/questions/839994/extracting-a-url-in-python"
>>> print re.findall(r'(https?://[^s]+)', myString)
['http://www.google.com', 'http://stackoverflow.com/questions/839994/extracting-a-url-in-python']
>>> 

这篇关于如何使用 python 从字符串中提取 url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆