使用 Python 抓取 Twitter

逆向工程 Python 联网 网站
2021-06-22 04:37:47

我一直在致力于一个项目,以使用非官方 API 和 Python 对 twitter 的应用程序进行逆向工程,以从 Twitter 上抓取公共帖子。(我想创建一个“替代”应用程序,它只是一个可以搜索用户并获取其帖子的本地主机)

我一直在搜索和阅读与 REST、AJAX 和 Python 模块 requests、requests-html、BeautifulSoup 等相关的所有内容。

在 devtools 上查看 twitter 时(例如在 Marvel 的个人资料页面上),我可以看到唯一发送的相关请求(通过 POST 和 GET)如下: client_event.json 和 UserTweets?variables=... 。我知道这些是通过清理网络选项卡并仅在我向下滚动并加载新推文时记录而收到的相关消息 - 这些是唯一出现的不是随机视频的消息(我使用 -video 清理了搜索 - init -csp_report -config -ondemand -like -pageview -recommendations -prefetch -jot -key_live_kn -svg -jpg -jpeg -png -ico -analytics -loader -sharedCore -Hebrew)。

我是这个领域的新手,所以我可能做错了什么。我可以在 UserTweets 上看到我正在寻找的响应——一个包含我需要的所有数据的漂亮 JSON——但我无法访问它,无论我尝试了多少。

我尝试了不同的模块和不同的标题,但我一无所获。我不想使用 Selenium,因为它很烦人,而且我知道我需要的数据存储在哪里。 我想要的 JSON

我一直在尝试将 GET 请求发送到:https ://twitter.com/i/api/graphql/vamMfA41UoKXUmppa9PhSw/UserTweets ? variables =% 7B%22userId%22%3A%2215687962%22%2C%22count%22 %3A20%2C%22cursor%22%3A%22HBaIgLLN%2BKGEryYAAA%3D%3D%22%2C%22withHighlightedLabel%22%3Atrue%2C%22withTweetQuoteCount%22%3Atrue%2C%22include2Promoted%2AT %3Afalse%2C%22withUserResults%22%3Afalse%2C%22withVoice%22%3Afalse%2C%22withNonLegacyCard%22%3Atrue%7D

通过做:

from requests_html import HTMLSession
from bs4 import BeautifulSoup

response = session.get('https://twitter.com/i/api/graphql/vamMfA41UoKXUmppa9PhSw/UserTweets?variables=%7B%22userId%22%3A%2215687962%22%2C%22count%22%3A20%2C%22cursor%22%3A%22HBaIgLLN%2BKGEryYAAA%3D%3D%22%2C%22withHighlightedLabel%22%3Atrue%2C%22withTweetQuoteCount%22%3Atrue%2C%22includePromotedContent%22%3Atrue%2C%22withTweetResult%22%3Afalse%2C%22withUserResults%22%3Afalse%2C%22withVoice%22%3Afalse%2C%22withNonLegacyCard%22%3Atrue%7D')
response.html.render()
s = BeautifulSoup(response.html.html, 'lxml')

但我得到一个 HTML 脚本,要么说 Chromium 不受支持,要么只是一个没有 javascript 更新 DOM 的静态页面。

所有帮助表示赞赏。

谢谢

0个回答
没有发现任何回复~