我遇到以下错误我想获取特定用户的最新推文,请您帮忙。 BeautifulSoup - AttributeError:“NoneType”对象没有属性“find”
import requests
from bs4 import BeautifulSoup
def get_last_tweet_link(username):
"""
Gets the link to the last tweet of a user on Twitter.
Args:
username: The username of the user on Twitter.
Returns:
The link to the last tweet of the user.
"""
# Get the HTML of the user's Twitter page.
url = "https://twitter.com/" + username
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
# Find the last tweet.
last_tweet = soup.find("div", class_="tweet")
# Get the link to the last tweet.
link = last_tweet.find("a", class_="tweet-link").get("href")
return link
if __name__ == "__main__":
# Get the link to the last tweet of the user "elonmusk".
link = get_last_tweet_link("elonmusk")
# Print the link to the last tweet.
print(link)
代码首先导入requests和BeautifulSoup库。然后,它定义了一个名为 get_last_tweet_link 的函数。此函数采用一个参数,即您想要获取其最后一条推文链接的 Twitter 用户的用户名。
该函数首先通过调用requests.get函数获取用户Twitter页面的HTML。然后它使用 BeautifulSoup 库来解析 HTML 并创建一个 Python 对象。
我需要有人帮助我修复代码
您收到此错误,因为未找到
soup.find("div", class_="tweet")
,因此它返回了错误。
据我所知,Twitter 不再返回 HTML 响应。相反,他们发送呈现页面的 JavaScript 代码。这意味着 requests 模块不能用于抓取 Twitter 数据,并且使用 Selenium 可能会导致被 Twitter 屏蔽。我建议使用官方 Twitter API,该 API 位于 https://developer.twitter.com/en/docs/twitter-api,但它不是免费的。