【问题标题】:Extracting external links from tweets in python从python中的推文中提取外部链接
【发布时间】:2023-03-08 16:20:02
【问题描述】:

我编写了这个简单的程序来从某个用户的推文中提取链接。我能够提取推文中的链接,但似乎我得到的只是以 t.co 作为域的链接。这些链接指向其他推文。

问题是这些链接有时会导致其他推文。如何从推文中获取链接并确保这些链接是针对外部网站的,而不是针对推特本身的。

我希望我的问题很清楚,因为这是我描述它的最佳方式。

谢谢

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import re

#http://www.tweepy.org/
import tweepy

#Get your Twitter API credentials and enter them here
consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""

#method to get a user's last  200 tweets
def get_tweets(username):

        #http://tweepy.readthedocs.org/en/v3.1.0/getting_started.html#api
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_key, access_secret)
        api = tweepy.API(auth)

        #set count to however many tweets you want; twitter only allows 200 at once
        number_of_tweets = 200

        #get tweets
        tweets = api.user_timeline(screen_name = username,count = number_of_tweets)

        for tweet in tweets:
                urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tweet.text)
                for url in urls:
                        print url


#if we're running this as a script
if __name__ == '__main__':

    #get tweets for username passed at command line
    if len(sys.argv) == 2:
        get_tweets(sys.argv[1])
    else:
        print "Error: enter one username"

    #alternative method: loop through multiple users
        # users = ['user1','user2']

        # for user in users:
#       get_tweets(user)

这是一个输出示例:(我无法发布它,因为它有缩短的链接)。编辑不允许我这样做。

【问题讨论】:

    标签: python api twitter


    【解决方案1】:

    在 Python3 中,你可以做Greg Filla的回答如下:

    import urllib
    
    for tweet in tweets:
    urls = re.findall("http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", tweet.text)
    for url in urls:
        try:
            opener = urllib.request.build_opener()
            request = urllib.request.Request(url)
            response = opener.open(request)
            actual_url = response.geturl()
            print(actual_url)
        except:
            print(url)
    

    【讨论】:

      【解决方案2】:

      您需要获取重定向的 URL。首先,添加import urllib2,然后尝试以下代码:

      for tweet in tweets:
          urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tweet.text)
          for url in urls:
              try:
                  res = urllib2.urlopen(url)
                  actual_url = res.geturl()
                  print actual_url
              except:
                  print url
      

      我有 try..except 块,因为我测试的一些推文提取了无效的 URL。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-10
        • 2013-08-29
        • 2013-05-13
        • 2012-12-15
        相关资源
        最近更新 更多