如何通过reddit bot发送抓取的数据

时间:2016-06-22 18:02:53

标签: python web-scraping bots reddit

所以我有这个机器人,我想用它来回复mets游戏的盒子分数,只要有人说" mets得分"在特定的subreddit上。这是我的第一个python项目,我打算在我作为学习工具创建的虚拟subreddit上使用它。我在浏览机器人的网站上发送分数时遇到了麻烦,因此它可以出现在对#t; mets得分的回复中#34;评论。有什么建议吗?

import praw
import time
from lxml import html
import requests
from bs4 import BeautifulSoup

r = praw.Reddit(user_agent = 'my_first_bot')
r.login('user_name', 'password')

def scores():
soup = BeautifulSoup(requests.get("http://scores.nbcsports.com/mlb/scoreboard.asp?day=20160621&meta=true").content, "lxml")

table = soup.find("a",class_="teamName", text="NY Mets").find_previous("table")
a, b = [a.text for a in table.find_all("a",class_="teamName")]
inn, a_score, b_score = ([td.text for td in row.select("td.shsTotD")] for row in table.find_all("tr"))
print (" ".join(inn))
print ("{}: {}".format(a, " ".join(a_score)))
print ("{}: {}".format(b, " ".join(b_score)))


words_to_match = ['mets score']
cache = []

def run_bot():
    print("Grabbing subreddit...")
    subreddit = r.get_subreddit("random_subreddit")
    print("Grabbing comments...")
    comments = subreddit.get_comments(limit=40)
    for comment in comments:
        print(comment.id)
        comment_text = comment.body.lower()
        isMatch = any(string in comment_text for string in words_to_match)
        if comment.id not in cache and isMatch:
            print("match found!"  + comment.id)
            comment.reply('heres the score to last nights mets game...' scores())
            print("reply successful")
            cache.append(comment.id)
            print("loop finished, goodnight")

while True:
    run_bot()
    time.sleep(120)

1 个答案:

答案 0 :(得分:0)

我想我会让你摆脱痛苦;)。您的代码段存在多个问题:

comment.reply('heres the score to last nights mets game...' scores())

.reply()方法需要一个字符串或一个对象,它可以具有足够好的表示形式作为字符串。假设方法scores()返回一个字符串,你应该连接两个参数,如下所示:

comment.reply('heres the score to last nights mets game...'+ scores())

看起来你对基本python语法和结构的了解是多尘的。如需快速复习,请参阅this.

您的方法scores()不会返回任何内容。它只打印出一堆行(我假设它们用于调试目的)。

def scores():
    soup = BeautifulSoup(requests.get("http://scores.nbcsports.com/mlb/scoreboard.asp?day=20160621&meta=true").content, "lxml")
    .......    
    print (" ".join(inn))
    print ("{}: {}".format(a, " ".join(a_score)))
    print ("{}: {}".format(b, " ".join(b_score)))

有趣的是,您可以使用这些确切的字符串作为您的返回值(或者可能完全符合您的需要):

def scores():
    .......
    inn_string = " ".join(inn)
    a_string = "{}: {}".format(a, " ".join(a_score))
    b_string = "{}: {}".format(b, " ".join(b_score))
    return "\n".join([inn_string, a_string, b_string])

这些应该让你起步并运行。

更多建议:您是否阅读了Reddit PRAW docs?应该阅读的内容。您还应该使用praw.helpers.comment_stream()。它简单易用,可以为您检索新的评论。目前,您尝试每120秒最多获取40条评论。当120秒跨度中存在多个相关评论时会发生什么。您最终会遗漏一些您应该回复的评论。 .comment_stream()将为您处理速率限制,以便您的机器人可以按照自己的节奏回复每个需要注意的新评论。详细了解此here.

相关问题