【问题标题】:How to extract or grab all shortened URLs from a tweet?如何从推文中提取或抓取所有缩短的 URL?
【发布时间】:2018-01-31 19:12:02
【问题描述】:

如果有的话,我想从推文中提取缩短的 URL。这些 URL 遵循标准格式:http://t.co (details here)

为此,我使用了以下正则表达式,当我通过将文本存储为字符串来测试推文文本时,该表达式运行良好。

注意: 我使用 https://shortnedurl/string 而不是真正的缩短 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

但是,当我使用其 API 从 twitter 读取推文并在其上运行相同的正则表达式时,我得到以下输出,这是不可取的。

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

它似乎正在获取 twitter ID 的 URL,以及一个主题标签。

我该如何处理这个问题?我只想阅读这些http://t.co URL。

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

printing urls https://https://shortnedurl/string
printing urls https://https://shortnedurl/string>https://https://shortnedurl/string</a></span>

我不知道为什么用&lt;/a&gt;&lt;span&gt; 再次找到相同的URL。

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

printing urls https://https://shortnedurl/string>https://https://shortnedurl/string</a></span>

更新 2: 推文文本看起来与我预期的有点不同:

    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>

【问题讨论】:

    标签: python regex python-2.7 twitter web-scraping


    【解决方案1】:

    你可以使用正则表达式

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

    【讨论】:

    • S+ 不起作用。它将两个正常 url 与嘈杂的 url 组合在一个字符串中,从而导致无效的 url。查看更新。
    • 我认为这与普通字符串和推文文本形式有关。查看我的更新 2。
    • "(https?:\/\/shortnedurl\.com\/\S+)" 将与""匹配,您可以在另一个步骤中删除""
    • 我接受你的回答。也许将这些 cmets 添加到您的答案中是个好主意。
    【解决方案2】:

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

    https?://shortnedurl.com/\S*
    # look for http or https:://
    # shortnedurl.com/ literally
    # followed by anything not a whitespace character, 0+
    

    a demo on regex101.com
    对于您的特殊情况:

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

    【讨论】:

      猜你喜欢
      • 2021-03-13
      • 2021-06-16
      • 2011-05-11
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2018-07-11
      • 1970-01-01
      相关资源
      最近更新 更多