【发布时间】:2019-01-31 12:24:36
【问题描述】:
我正在尝试在特定时间范围内从一个网页上抓取推文。
为此,我使用此链接,该链接仅在我指定的时间范围内搜索:
https://twitter.com/search?f=tweets&q=subwaydstats%20since%3A2016-08-22%20until%3A2018-08-22
这是我的代码:
import pandas as pd
import datetime as dt
import urllib.request
from bs4 import BeautifulSoup
url = 'https://twitter.com/search?f=tweets&q=subwaydstats%20since%3A2016-08-22%20until%3A2018-08-22'
thepage = urllib.request.urlopen(url)
soup = BeautifulSoup(driver.page_source,"html.parser")
i = 1
for tweet in soup.find_all('div', {'class': 'js-tweet-text-container'}):
print(tweet.find('p', {'class': 'TweetTextSize'}).text.encode('UTF-8'))
print(i)
i += 1
当我从地铁统计用户的实际 twitter 页面中抓取时,上面的代码有效。
出于这个原因,我不明白为什么它对搜索页面不起作用,即使 html 对我来说似乎是一样的。
我是一个初学者,如果这是一个愚蠢的问题,我很抱歉。谢谢!
【问题讨论】:
-
Twitter 确实提供了一个您可以使用的 API。标准搜索 API 的文档:developer.twitter.com/en/docs/tweets/search/api-reference/…
-
还有一个非官方的 Python 包装器可以让对 api 的请求变得更加容易:github.com/bear/python-twitter
-
您好,我考虑过使用 API,但它只能让您获取过去 7 天的推文。我想我可以让它不断生成并将它们存储在某个地方,但我正在尝试寻找替代方法。
-
抓取 Twitter 网站违反了 Twitter 服务条款,如果检测到这种情况,您的 IP 地址可能会被阻止。见 twitter.com/tos
标签: python html twitter beautifulsoup