[英]How to run snscrape command from python script?
我正在嘗試使用snscrape下載一些推文。 安裝后,我可以運行如下命令來下載一些推文:
snscrape --jsonl --max-results 4 twitter-search "#SherlockHolmes since:2015-01-01 until:2015-01-15" > sherlock_tweets.json
現在我想從 python 腳本中運行這個命令。 據我了解,這樣做的方法是使用 subprocess.run 方法。 我使用以下代碼從 python 運行命令:
import subprocess
# Running this in a terminal works
cmd = '''snscrape --jsonl --max-results 4 twitter-search "#SherlockHolmes since:2015-01-01 until:2015-01-15" > sherlock_tweets.json'''
arglist = cmd.split(" ")
process = subprocess.run(arglist, shell=True)
但是,運行它會出現以下錯誤。
usage: snscrape [-h] [--version] [-v] [--dump-locals] [--retry N] [-n N] [-f FORMAT | --jsonl] [--with-entity] [--since DATETIME] [--progress]
{telegram-channel,weibo-user,vkontakte-user,instagram-user,instagram-hashtag,instagram-location,twitter-thread,twitter-search,reddit-user,reddit-subreddit,reddit-search,facebook-group,twitter-user,twitter-hashtag,twitter-list-posts,facebook-user,facebook-community,twitter-profile}
...
snscrape: error: the following arguments are required: scraper
為什么這兩種情況下的行為不一樣? 我如何完成從 python 腳本運行命令,獲得與在終端中輸入它完全相同的行為?
我不知道您是否找到了解決方案,但我運行了此代碼並且對我有用:
import pandas as pd
import snscrape.modules.twitter as sntwitter
tweet_collection = pd.DataFrame({
'Username':[],
'Date'=[],
'Likes'=[],
'Content'=[]})
for tweet in sntwitter.TwitterSearchScraper(f'since:{date_beg} until:{date_end} from:{twitter_account}').get_items():
tweets_collection = tweets_candidats.append({
"Username":tweet.user.username,
"Date":tweet.date,
"Tweet":tweet.content,
"Likes":tweet.likeCount,},ignore_index=True)
tweets_candidats.to_csv('Path/file.csv')
您可以在 git hub 上的代碼中找到更多詳細信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.