Python 如何从tweet中提取或抓取所有缩短的URL?

Python 如何从tweet中提取或抓取所有缩短的URL?,python,regex,python-2.7,twitter,web-scraping,Python,Regex,Python 2.7,Twitter,Web Scraping,我想从推文中提取缩短的URL(如果有的话)。这些URL遵循标准格式:() 为此,我使用了下面的正则表达式,当我用tweet文本测试它时,它工作得很好,只将文本存储为字符串 注意: 我使用的不是真正缩短的URL,因为StackOverflow不允许在这里发布这样的URL 示例代码: import re tweet = "Grim discovery in the USS McCain collision probe https://shortnedurl.com @MattRiversCNN r

我想从推文中提取缩短的URL(如果有的话)。这些URL遵循标准格式:()

为此,我使用了下面的正则表达式,当我用tweet文本测试它时,它工作得很好,只将文本存储为字符串

注意: 我使用的不是真正缩短的URL,因为StackOverflow不允许在这里发布这样的URL

示例代码:

import re

tweet = "Grim discovery in the USS McCain collision probe https://shortnedurl.com @MattRiversCNN reports #TheLead"

urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
                  tweet)
for url in urls:
    print "printing urls", url 
此代码的输出:

printing urls https://shortnedurl.com
然而,当我使用twitter的API从twitter上读取tweet并在其上运行相同的正则表达式时,我得到了以下不受欢迎的输出

printing urls https://https://shortnedurl/string
printing urls https://https://shortnedurl/string</a></span>
printing urls https://twitter.com/MattRiversCNN
printing urls https://twitter.com/search?q=%23TheLead
打印URLhttps://https://shortnedurl/string
打印URLhttps://https://shortnedurl/string
打印URLhttps://twitter.com/MattRiversCNN
打印URLhttps://twitter.com/search?q=%23TheLead
它似乎得到了twitter ID的URL,以及一个标签

我如何处理这个问题?我只想阅读这些网址

更新1: 我尝试了https?://t.co/\S*,但是,我仍然得到以下嘈杂的url:

printing urls https://https://shortnedurl/string
printing urls https://https://shortnedurl/string>https://https://shortnedurl/string</a></span>
打印URLhttps://https://shortnedurl/string
打印URLhttps://https://shortnedurl/string>https://https://shortnedurl/string
我不知道为什么在
中再次找到相同的URL

对于https?://t.co/\S+,我得到了无效的URL,因为它将上述两个URL合并在一个URL中:

printing urls https://https://shortnedurl/string>https://https://shortnedurl/string</a></span>
打印URLhttps://https://shortnedurl/string>https://https://shortnedurl/string
更新2: tweet文本看起来与我预期的略有不同:

    Grim discovery in the USS McCain collision probe 
<span class="link"><a href="https://shortenedurl">https://shortenedurl</a></span> <span class="username"><a 
href="https://twitter.com/MattRiversCNN">@MattRiversCNN</a></span>
     reports <span class="tag"><a href="https://twitter.com/search?
    q=%23TheLead">#TheLead</a></span>
USS McCain碰撞探测器中的可怕发现
报告

如果我理解正确,只需将希望包含在正则表达式中的字符串放入,如下所示:

https?://shortnedurl.com/\S*
# look for http or https:://
# shortnedurl.com/ literally
# followed by anything not a whitespace character, 0+
请参阅。
对于您的特殊情况:

https?://t\.co/\S*
您可以使用正则表达式

https?://t\.co/\S+

S+不起作用。它将两个正常url与嘈杂的url组合在一个字符串中,从而导致无效url。请看更新。我认为这与普通字符串和tweet文本形式有关。请参阅我的更新2。“(https?:\/\/shortnedurl\.com\/\S+”将与“”匹配,您可以在其他步骤中删除“”,我接受您的答案。也许将这些评论添加到你的答案中是个好主意。