【问题标题】:Grabbing data using selenium and adding it to a dictionary for use in a dataframe使用 selenium 抓取数据并将其添加到字典中以在数据帧中使用
【发布时间】:2019-02-04 20:19:56
【问题描述】:

我一直在尝试使用 selenium 从 twitter 上抓取推文。我已经成功地获得了我想要的 html 并打印了它,但是我无法进入适合用于数据框的表单。

这是我的代码:

import time
import pandas as pd
import numpy as np

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

browser = webdriver.Chrome()
url = 'https://twitter.com/search?f=tweets&q=cuomosmta%20since%3A2016-08-22%20until%3A2018-08-22'

browser.get(url)
time.sleep(1)

tweet_dict = {}

tweets = browser.find_elements_by_class_name('tweet-text')

for tweet in tweets:
    print(tweet.text)
    tweet_dict['tweet'] = tweet.text

如果您运行代码,您会看到它打印了每条单独的推文。我这样做是为了确保代码正常工作。

但由于某种原因,当我查看我的字典时,我的输出来自:

tweet_dic['tweet']

是:

'Ugh, Cuomo and #CuomosMTA are terrible, just terrible.'

上面的输出也是页面上我想要抓取的最后一条推文。

我已经尝试了多种方法,甚至尝试过 BeautifulSoup,但由于某种原因,我一直得到相同的结果。

我不明白为什么我可以打印所有推文但不能将它们附加到字典中。

我是初学者,可能遗漏了一些非常明显的东西,因此我们将不胜感激。

请,如果可能的话,我尽量只使用 selenium,因为它比在 beautifulsoup 中更容易获取确切的时间戳。

谢谢!

【问题讨论】:

    标签: python selenium twitter


    【解决方案1】:

    字典应该只包含唯一的键,所以不是在循环中附加每条推文,而是覆盖相同的键值对。您可以尝试以下解决方案:

    for tweet in range(len(tweets)):
        print(tweets[tweet].text)
        tweet_dict['tweet_%s' % tweet] = tweets[tweet].text
    

    输出应该是

    {'tweet_0': 'first tweet content', 'tweet_1': 'second tweet content', ...}
    

    【讨论】:

    • 非常感谢。我唯一的问题是 ['tweet_%s' % tweet] 的实际含义。如果您能指导我完成,我将不胜感激。
    • 这是(其中一种方式)字符串连接在 Python 中的工作方式:%s 是一个字符串占位符,意味着它将被实际的字符串值替换。 % tweet 正是您传递的内容,而不是占位符。你也可以将更多的子字符串传递为"here comes %s and %s" % ("first", "second"),这样它就会被执行为"fere comes first and second"
    • @agra94 你可以accept/upvote 答案,以防它解决了你的问题/对你的previous question 有用的答案之一
    • 当然,抱歉。直到今天我才能投票,因为我没有足够的声誉。
    猜你喜欢
    • 2016-05-27
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2020-02-09
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多