簡體   English   中英

Twitter 不再適用於請求庫 python

[英]Twitter no longer works with requests library python

我有一個使用請求庫的 python function 和 BeautifulSoup 來抓取特定用戶的推文。

import requests
from bs4 import BeautifulSoup

contents = requests.get("https://twitter.com/user")
soup = BeautifulSoup(contents.text, "html.parser")

當 requests 庫訪問 Twitter 時,它使用的是舊版本的 Twitter。 但是,由於 Twitter 最近放棄了對其舊版本的支持,請求庫不再工作並返回 html 代碼,說明此版本的 Twitter 已過期。

有沒有辦法讓請求庫訪問較新版本的 Twitter?

requests庫將訪問您傳遞的 URL。 我建議檢查Twitter API 文檔並更新您的代碼以對應最新版本。

無法直接回答(也沒有足夠的評論點),但遇到同樣的問題,我確實找到了一些新工具。 https://github.com/bisguzar/twitter-scraper使用 requests_html 來獲取推文(參見他們的 tweets.py 模塊)。 https://github.com/Mottl/GetOldTweets3/是另一個強大的 python 推文抓取工具。

我也遇到了這個問題。 其根本原因是 Twitter 拒絕“舊版”瀏覽器,不幸的是其中包含 Python 的 requests 庫。

Twitter 通過查看作為請求的一部分發送的User-Agent header 來確定您正在使用的瀏覽器。 所以我對這個問題的解決方案就是簡單地欺騙這個 header。

在您的特定情況下,請嘗試執行以下操作;

import requests
from bs4 import BeautifulSoup

contents = requests.get(
    "https://twitter.com/user",
    headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"}
)
soup = BeautifulSoup(contents.text, "html.parser")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM