python - 如何在 Python 中使用 twitter API 提取包含特定关键字的推文位置

标签 python python-3.x pandas tweepy

我正在尝试提取包含特定关键字及其地理位置的所有推文。

例如,我想从'france''singapore'下载所有包含关键字'iphone'的英文推文

我的代码

import tweepy
import csv
import pandas as pd
import sys

# API credentials here
consumer_key = 'INSERT CONSUMER KEY HERE'
consumer_secret = 'INSERT CONSUMER SECRET HERE'
access_token = 'INSERT ACCESS TOKEN HERE'
access_token_secret = 'INSERT ACCESS TOKEN SECRET HERE'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True,wait_on_rate_limit_notify=True)

# Search word/hashtag value 
HashValue = ""

# search start date value. the search will start from this date to the current date.
StartDate = ""

# getting the search word/hashtag and date range from user
HashValue = input("Enter the hashtag you want the tweets to be downloaded for: ")
StartDate = input("Enter the start date in this format yyyy-mm-dd: ")

# Open/Create a file to append data
csvFile = open(HashValue+'.csv', 'a')

#Use csv Writer
csvWriter = csv.writer(csvFile)

for tweet in tweepy.Cursor(api.search,q=HashValue,count=20,lang="en",since=StartDate, tweet_mode='extended').items():
    print (tweet.created_at, tweet.full_text)
    csvWriter.writerow([tweet.created_at, tweet.full_text.encode('utf-8')])

print ("Scraping finished and saved to "+HashValue+".csv")
#sys.exit()

如何做到这一点。

最佳答案

-你好-拉胡尔

据我了解,您希望从搜索的推文中获取地理数据,而不是根据地理编码过滤搜索。

这是一个代码示例,其中包含您感兴趣的相关字段。这些可能会或可能不会提供,具体取决于推特隐私设置。

请注意搜索 API 中没有“since”参数:

https://tweepy.readthedocs.io/en/latest/api.html#help-methods

https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets

标准 twitter api 搜索可追溯到 7 天。高级和企业 API 具有 30 天搜索以及完整存档搜索,但您需要支付 $$$。

不幸的是,tweepy 仍然没有记录他们的模型:

https://github.com/tweepy/tweepy/issues/720

所以如果你想查看 tweet 对象,你可以使用 pprint 包并运行:

pprint(tweet.__dict__)

我注意到的一个区别是 JSON 中的“文本”字段在对象中变成了“全文”。

如果您发现的推文是引用推文,则那里还有关于原始推文的信息,与我看到的信息相同。

无论如何,这是代码,我在测试时添加了一个最大推文计数以循环遍历光标,以避免违反任何 API 限制。

如果您需要 csv 代码,请告诉我,但看起来您已经可以处理了。

import tweepy

# API credentials here
consumer_key = 'your-info'
consumer_secret = 'your-info'
access_token = 'your-info'
access_token_secret = 'your-info'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True,wait_on_rate_limit_notify=True)

searchString = "iPhone"

cursor = tweepy.Cursor(api.search, q=searchString, count=20, lang="en", tweet_mode='extended')

maxCount = 1
count = 0
for tweet in cursor.items():    
    print()
    print("Tweet Information")
    print("================================")
    print("Text: ", tweet.full_text)
    print("Geo: ", tweet.geo)
    print("Coordinates: ", tweet.coordinates)
    print("Place: ", tweet.place)
    print()

    print("User Information")
    print("================================")
    print("Location: ", tweet.user.location)
    print("Geo Enabled? ", tweet.user.geo_enabled)

    count = count + 1
    if count == maxCount:
        break;

会输出这样的东西:

Tweet Information
================================
Text:  NowPlaying : Hashfinger - Leaving
https://derp.com

#iPhone free app https://derp.com
#peripouwebradio
Geo:  None
Coordinates:  None
Place:  None

User Information
================================
Location:  Greece
Geo Enabled?  True

关于python - 如何在 Python 中使用 twitter API 提取包含特定关键字的推文位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56862572/

相关文章:

python - 将Python中的负索引转换为正索引

python - 使用 Scrapy 从抓取的数据中构造 DataFrame

python - 为什么我在编辑全局变量时会出现类型错误?

python - string.translate() 不接受 2 个参数

python - 如何使 python 导入模块和文件夹一起导入?

python模块 'pandas'没有属性 'plotting'

python - 在每一行 Pandas 中,从第一个非 NaN 开始,X 值的窗口保持不变,而所有其他值都是 NaN

python - 在 Django 中单击后找不到页面

python - 定义一个函数,该函数接受项目列表并返回以逗号分隔的项目名称列表

python - 在 Pandas DataFrame 中使用 set_index