【问题标题】:How to run snscrape command from python script?如何从 python 脚本运行 snscrape 命令?
【发布时间】:2021-02-13 01:57:57
【问题描述】:

我正在尝试使用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 脚本运行命令,获得与在终端中输入完全相同的行为?

【问题讨论】:

  • 您可以尝试发送整个字符串而不是按空格分割吗?或者尝试将命令定义为列表文字,这样您的参数就不会在错误的点被拆分?
  • 为什么要用三个单引号来指定 cmd?
  • 传递字符串确实有效。我认为出于某种原因有必要拆分为一个列表,谢谢。

标签: python bash subprocess


【解决方案1】:

我不知道你是否找到了解决方案,但我运行了这段代码并且对我有用:

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 上的代码中找到更多详细信息

Twitter snscrape arguments

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多