首页 > 解决方案 > Python Geo Scrape 使用 Tweepy

问题描述

我正在使用 Twitter 的 API,并tweepy希望从 Tweets 中抓取可用的地理位置坐标。我的最终目标是仅将每条推文的坐标存储在表格中。

我的问题是,当定位推文时,我遇到了一个错误,其中提供了比坐标更多的信息:

较早的尝试

到目前为止,我的代码如下:


import pandas as pd
import json
import tweepy
import csv

class MyStreamListener(tweepy.StreamListener):

    def on_status(self, status):

        if status.retweeted:
            return

        if True:

            coords = status.coordinates
            geo = status.geo

        if geo is not None:
            geo = json.dumps(geo)

        if coords is not None:
            coords = json.dumps(coords)    

            print(coords, geo)
            with open('coordinates_data.csv', 'a') as f:
                writer = csv.writer(f)
                writer.writerow([coords,geo])


    def on_error(self, status_code):
        if status_code == 420:
            #returning False in on_error disconnects the stream
            return False

LOCATIONS = [-124.7771694, 24.520833, -66.947028, 49.384472,        # Contiguous US
                 -164.639405, 58.806859, -144.152365, 71.76871,         # Alaska
                 -160.161542, 18.776344, -154.641396, 22.878623]        # Hawaii

auth = tweepy.OAuthHandler('access auths', 'access auths')
auth.set_access_token('token','token')

api = tweepy.API(auth)
user = api.me()

myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener)  
myStream.filter(locations=LOCATIONS)

我确定这个问题与我缺乏对“json”的理解有关,或者我需要使用数据字典。

我将不胜感激任何帮助!

标签: pythonjsonapidictionarytweepy

解决方案


澄清一下,Tweepy 是一个与 Twitter 的 API 接口的第三方库。

这就是 Twitter 表示坐标对象的方式。Tweepy 将/ Tweet 对象coordinates数据的属性解析为字典。您可以简单地访问该字段作为该字典的键,以获取包含经度和纬度值的列表。Statuscoordinates

您还缺少一个引号,',您在哪里初始化auth,但我认为这是您替换此问题的凭据时的拼写错误。


推荐阅读