【发布时间】: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 中更容易获取确切的时间戳。
谢谢!
【问题讨论】: