在Twitter上使用BeautifulSoup获得转推计数

时间:2018-03-18 18:14:45

标签: python twitter beautifulsoup

我知道我可以使用Twitter API,但我正在尝试使用BeautifulSoup来提取以下示例推文的转推计数:

from bs4 import BeautifulSoup

soup = 
BeautifulSoup('https://twitter.com/dog_rates/status/758828659922702336', 
'lxml')

retweet_count = soup.find('div', {'class': 'js-tweet-stats-container tweet-
stats-container'}).find('ul', {'class': 'stats'}).find('li', {'class': 'js-
stat-count js-stat-retweets stat-count'}).contents

print(retweet_count)

我正在尝试打印出“内容”,以便我可以看到接下来要去哪里提取转推计数(此示例目前为4,288)。

然而,即使在这个阶段,我也会收到以下错误:

AttributeError: 'NoneType' object has no attribute 'find'

如果有人能告诉我哪里出错了,我将非常感激。

由于

1 个答案:

答案 0 :(得分:-1)

BeautifulSoup对象采用表示标记的字符串作为参数(请参阅Making the soup)。您需要先获取页面内容。例如,使用requests库:

import requests

html = requests.get('https://twitter.com/dog_rates/status/758828659922702336').text

另一个问题是您没有访问包含转推计数的元素。结果是几个标记元素:

<li aria-hidden="true" class="js-stat-count js-stat-retweets stat-count">
<a class="request-retweeted-popup" data-activity-popup-title="4,288 retweets" data-compact-localized-count="4.3K" data-tweet-stat-count="4288" role="button" tabindex="0">
<strong>4,288</strong> Retweets
      </a>
</li>

要解决此问题,您需要调用find来获取锚标记,并使用attrs字典获取data-tweet-stat-count属性:{{1 }}

获得转推计数的最终产品是:

.attrs["data-tweet-stat-count"]

打印出import requests from bs4 import BeautifulSoup html = requests.get('https://twitter.com/dog_rates/status/758828659922702336').text soup = BeautifulSoup(html, 'lxml') retweet_count = soup.find( 'div', {'class': 'js-tweet-stats-container tweet-stats-container'} ).find( 'ul', {'class': 'stats'} ).find( 'li', {'class': 'js-stat-count js-stat-retweets stat-count'} ).find( 'a', {'class': 'request-retweeted-popup'} ).attrs["data-tweet-stat-count"] print(retweet_count)

相关问题