python - 当 expanded_url 不够时在 Tweepy 中完成 url(与 urllib2 集成?)

标签 python python-2.7 urllib2 tweepy

我最近开始使用 Tweepy,尤其是 api.user_timeline。我的脚本从用户那里下载一系列推文,并将 Tweepy Status 调用中提供的各种详细信息的大部分打印到一个文本文件中。我的问题是从推特上反转小网址。我在该站点的一个答案中读到,解决该问题的正确方法是在 Twitter 实体中使用“expanded_url”命令,这就是我所做的。这是我的代码:

import tweepy
import codecs


auth = tweepy.OAuthHandler("xxx", "xxx")
auth.set_access_token("yyy", "yyy")

with codecs.open("file.txt", encoding='utf-8', mode='w+') as f:
   api = tweepy.API(auth)
   for status in tweepy.Cursor(api.user_timeline, "xxx", include_entities=True).items():
    ...
    # Extracting info from the entities
       for hashtag in status.entities['hashtags']:
           f.write(format(hashtag['text']))


       for url in status.entities['urls']:
           f.write(format(url['expanded_url']))

问题是这些扩展的 url 并不总是我需要的完整 url。例如,有问题的推文代码给了我“http://goo.gl/sOH17n” ' 这仍然隐藏了文章所来自的真实网站。我有一段代码,它通过 urllib2 为我提供了完整的 url,但是当我将它们放在一起时,我得到了一个'HTTPError: HTTP Error 403: Forbidden'。这是我的试用版不工作(它总是与之前的部分集成,所以它不是不通过身份验证的问题)

import urllib2
for url in status.entities['urls']:
        expanded_url=url['expanded_url']
        fullurl= urllib2.urlopen(expanded_url)
        f.write(format(fullurl.url))

所以,我的问题是,有没有办法在 Tweepy 中找到真正完整的 URL?如果不是,为什么与 urllib2 的集成不起作用?如果这个问题看起来微不足道,我深表歉意,但我似乎无法摆脱这个问题,而且 tweepy 的文档很粗略。

提前感谢您的回答!

最佳答案

该 URL 来自 Google,因此我认为 Tweepy 不会存储您点击该链接后 Google 会将您定向到的位置。您可以使用 httplib 找到它,(这样您就可以获得 HEAD,而无需完全获取它将加载的页面):

import httplib
from urlparse import urlparse

url = urlparse('http://goo.gl/sOH17n')    # split URL into components
conn = httplib.HTTPConnection(url.hostname, url.port)
conn.request('HEAD', url.path)            # just look at the headers
rsp = conn.getresponse()
if rsp.status in (301,401):               # resource moved (permanent|temporary)
    print rsp.getheader('location')
else:
    print url
conn.close()

当我运行它时,我得到一个 URL,而不是 403 错误。该错误通常表示您没有查看该页面的权限,所以我猜您提供的 URL 不是您发布的 URL。

关于python - 当 expanded_url 不够时在 Tweepy 中完成 url(与 urllib2 集成?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17910493/

相关文章:

Python 子进程帮助 - 不能使用 shell=true

python - 让用户输入变量用于以后的方程式

javascript - 获取在 Python 中使用 Javascript 生成的页面

python - 将 cURL 命令转换为 Python 的 urllib2

python - RASA - rasa 运行操作 - 本地主机问题

python - Python 中的模糊查找

image - 在按钮上调整图像

urllib2 - 使用 Pytube : signature = cipher. get_signature(js, stream ['s' ]) 出现错误 KeyError: 's'

python - 如何在丢失之前运行两次keras模型?

python - 根据数据框中的条件过滤数据