如何在Tweepy Cursor中添加Bounding Box限制Twitter推文采集范围
给Tweepy推文采集代码添加阿富汗地理范围限制
嘿,我来帮你把代码改成限定在阿富汗范围内采集推文~
首先得说明下:你用的Twitter Search API(也就是api.search)并不直接支持bounding_box参数(这个参数主要是给流式API用的),不过我们可以用geocode参数来实现近似的范围限定,或者通过指定阿富汗的Place ID来精准匹配。下面给你两种方案:
方案1:基于Bounding Box计算Geocode参数
你给出的阿富汗bounding box是(60.5284298033, 29.318572496, 75.1580277851, 38.4862816432)(格式:最小经度、最小纬度、最大经度、最大纬度),我们可以先算出这个区域的中心坐标和覆盖整个区域的半径:
- 中心纬度:
(29.318572496 + 38.4862816432) / 2 ≈ 33.9024 - 中心经度:
(60.5284298033 + 75.1580277851) / 2 ≈ 67.8432 - 半径:阿富汗东西跨度约1400km,南北约900km,设置800km半径可以完全覆盖整个国家
接下来把这个参数加到你的代码里就行,修改后的完整代码如下:
import sys import os import jsonpickle import tweepy import datetime import time consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxx' consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' auth = tweepy.AppAuthHandler(consumer_key, consumer_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) maxTweets = 1000000 tweetCount = 0 stamp = time.strftime('%b%d%y%H%M') filename = 'AFG'+stamp+'.json' print(filename) searchQuery = ('afghanistan OR elections') # 新增的geocode参数,限定阿富汗区域 geocode_param = "33.9024,67.8432,800km" with open(filename, 'w') as f: # 在api.search里添加geocode参数 for tweet in tweepy.Cursor(api.search, q=searchQuery, tweet_mode='extended', geocode=geocode_param).items(maxTweets): f.write(jsonpickle.encode(tweet._json, unpicklable=False) + '\n') tweetCount += 1 print("Downloaded {0} tweets.". format(tweetCount))
方案2:用Place ID精准匹配(更准确)
如果想要更精准的范围(避免geocode可能包含周边国家的推文),可以先获取阿富汗的Place ID,然后在搜索关键词里加入place:PLACE_ID:
- 先运行一段小代码获取阿富汗的Place ID:
places = api.search_geo(query="Afghanistan", granularity="country") place_id = places[0].id print("阿富汗的Place ID是:", place_id)
运行后会得到类似01706c5a6fca0698这样的ID(这个是固定的,你也可以直接用这个值)
- 修改你的
searchQuery:
searchQuery = ('(afghanistan OR elections) place:01706c5a6fca0698')
这样就只会采集发布在阿富汗境内的推文,精准度更高。
两种方案你可以根据需求选择,第一种更简单,第二种更精准~
内容的提问来源于stack exchange,提问作者Ambrish Dhaka
相关产品推荐
相关产品推荐

