【问题标题】:How do I print tweets from twitter?如何从 Twitter 打印推文?
【发布时间】:2019-12-10 14:21:22
【问题描述】:

我正在尝试从 twitter 上抓取推文以进行一个辅助项目。

输出有困难。

使用最新版本的 pycharm。

import urllib
import urllib.request
from bs4 import BeautifulSoup

theurl = "https://twitter.com/search?q=ghana%20and%20jollof&src=typed_query"
thepage = urllib.request.urlopen(theurl)


soup = BeautifulSoup(thepage, "html.parser")
i = 1
for tweets in soup.findAll('div', {
    "class": "css-901oao css-16my406 r-1qd0xha r-ad9z0x r-bcqeeo r-qvutc0"
}):
    print (i)
    print (tweets.find('span').text)
    i = i+1
    print(tweets)

我没有收到任何错误,但推文没有输出。

【问题讨论】:

  • 我相信,但我不完全确定,推文是通过 javascript 在浏览器中动态加载的。所以你不能动态加载推文。我想有一些 python 模块可以完成这项工作,比如tweepy

标签: python web-scraping twitter sentiment-analysis


【解决方案1】:

您应该使用 requests 库,而且您的请求中缺少 user-agent 标头,这对于 twitter 来说似乎是强制性的。

这是一个工作示例:

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 条推文,你需要检查网络选项卡并查看浏览器如何动态加载其余推文。

不过这很繁琐,我强烈建议使用直接调用 twitter api 的库,例如 https://github.com/twintproject/twint

【讨论】:

  • 非常感谢
猜你喜欢
  • 2013-02-02
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
  • 2013-03-26
  • 2014-09-04
  • 1970-01-01
  • 2014-07-07
相关资源
最近更新 更多