【问题标题】:Importing Social Media Followers [duplicate]导入社交媒体关注者 [重复]
【发布时间】:2018-08-28 18:14:30
【问题描述】:

我在 Python 2.7 上运行此代码一段时间,以便自动收集 Twitter 和 Instagram 上某些帐户的关注者数量。

此代码应该实时为我提供一名篮球运动员的 Twitter 和 Instagram 关注者数量。

代码本周停止工作,我找不到修复它的方法。如果有人有解决方案,我将不胜感激!

import requests
from json import loads

Username = "nolimittb"
r = requests.get('https://www.instagram.com/'+Username)
html = r.text.encode("utf-8")
text = html[html.index("window._sharedData = ")+21:]
text = (text[:text.index("};</script>")]+"}").replace('\\"', "")
dictionary= loads(text)
data = dictionary["entry_data"]["ProfilePage"][0][user]

print "Thomas Bryant Instagram:"
print str(data["followed_by"]["count"]) + ' Followers'

from bs4 import BeautifulSoup
import requests
username='nolimittb31'
url = 'https://www.twitter.com/'+username
r = requests.get(url)
soup = BeautifulSoup(r.content)

f = soup.find('li', class_="ProfileNav-item--followers")
title = f.find('a')['title']
print 'Thomas Bryant Twitter:'
print title

num_followers = int(title.split(' ')[0].replace(',',''))

【问题讨论】:

  • 它显示的错误是什么?
  • NameError: name 'user' is not defined
  • 谢谢,但不幸的是,我在@KeyurPotdar 的代码中遇到了同样的问题
  • 好吧,user 确实似乎没有定义。要么用 Username 替换它,要么定义它,如果它们不是同一个变量。
  • Instagram 可能已经更改了他们的代码,Twitter 确实有效

标签: python beautifulsoup jupyter-notebook


【解决方案1】:

如果你print dictionary["entry_data"]["ProfilePage"][0],那么你会得到这个:

{
    'logging_page_id': 'profilePage_1706986508',
    'show_suggested_profiles': False,
    'graphql': {
        'user': {
            'biography': "Official IG of TB?\nLos Angeles Lakers\nA Hoosier at heart!! \nI will never be the same.. In Jesus' name.. Amen??",
            'blocked_by_viewer': False,
            'country_block': False,
            'external_url': 'https://www.bookcameo.com/thomasbryant',
            'external_url_linkshimmed': 'https://l.instagram.com/?u=https%3A%2F%2Fwww.bookcameo.com%2Fthomasbryant&e=ATPQyJlxPSdd8tAG-VVbepnurfbkUgrQTP8OsVKTH6d3cSec9dSlcW7JCevxuXWdZb0UtCzc',
            'edge_followed_by': {
                'count': 62109
            },
            ...
        ...
    ...
}

它的结构与您尝试索引的结构略有不同。所以,如果你想从返回的数据中访问关注者,你需要访问./graphql/user/edge_followed_by/count。

你可以这样做:

print dictionary["entry_data"]["ProfilePage"][0]["graphql"]["user"]["edge_followed_by"]["count"]
# Outputs: 62115

或者直接修改你的代码,它看起来像这样:

...

data = dictionary["entry_data"]["ProfilePage"][0]["graphql"]["user"]

print "Thomas Bryant Instagram:"
print str(data["edge_followed_by"]["count"]) + ' Followers'

输出:

Thomas Bryant Instagram:
62115 Followers

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-12
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2014-10-09
    • 1970-01-01
    • 2013-08-22
    相关资源
    最近更新 更多