Python 如何从twitter打印推文?

Python 如何从twitter打印推文?,python,web-scraping,twitter,sentiment-analysis,Python,Web Scraping,Twitter,Sentiment Analysis,我正试图从推特上抓取推特作为一个辅助项目 在输出方面有困难的 使用最新版本的pycharm 导入URL库 导入urllib.request 从bs4导入BeautifulSoup URL=https://twitter.com/search?q=ghana%20and%20jollof&src=typed_query 页面=urllib.request.urlopentheurl soup=BeautifulSoupthepage,html.parser i=1 对于汤中的推文。findAll'

我正试图从推特上抓取推特作为一个辅助项目

在输出方面有困难的

使用最新版本的pycharm

导入URL库 导入urllib.request 从bs4导入BeautifulSoup URL=https://twitter.com/search?q=ghana%20and%20jollof&src=typed_query 页面=urllib.request.urlopentheurl soup=BeautifulSoupthepage,html.parser i=1 对于汤中的推文。findAll'div'{ 类别:css-901AO css-16my406 r-1qd0xha r-ad9z0x r-bcqeeo r-qvutc0 }: 打印i 打印推文。查找“span”。文本 i=i+1 打印推文
我没有收到任何错误,但是推文没有输出。

您应该使用请求库,而且您的请求中缺少用户代理标题,这似乎是推特的强制要求

以下是一个工作示例:

import requests
from bs4 import BeautifulSoup

# without this you get strange reponses
headers = {
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
}

# the correct way to pass the arguments
params = (
    ('q', 'ghana and jollof'),
    ('src', 'typed_query'),
)

r = requests.get('https://twitter.com/search', headers=headers, params=params)
soup = BeautifulSoup(r.content, 'html.parser')
allTweetsContainers = soup.findAll("div", {"class": "tweet"})

print(len(allTweetsContainers))
# all that remains is to parse the tweets one by one
问题是,通过这种方式,每个请求只加载20条tweet,您需要检查“网络”选项卡,并查看浏览器如何动态加载其余的tweet


然而,这是非常乏味的,我强烈建议使用一个直接调用twitterapi的库,比如我相信,但我不完全确定tweet是否通过javascript动态加载到浏览器中。所以你不能动态加载推文。我想有一些python模块可以完成这项工作,非常感谢