python - 网络抓取 Instagram 关注者数量 BeautifulSoup

标签 python web-scraping beautifulsoup instagram

我刚刚开始学习如何使用 BeautifulSoup 进行网络抓取,并想编写一个简单的程序来获取给定 Instagram 页面的关注者数量。我目前有以下脚本(从另一个问答线程中提取):

import requests
from bs4 import BeautifulSoup

user = "espn"
url = 'https://www.instagram.com/'+ user
r = requests.get(url)
soup = BeautifulSoup(r.content)
followers = soup.find('meta', {'name': 'description'})['content']
follower_count = followers.split('Followers')[0]
print(follower_count)

# 10.7m

我遇到的问题是我想获得一个更精确的数字,当您将鼠标悬停在 Instagram 页面上的关注者数量上时您可以看到该数字(例如 10,770,816)。

不幸的是,我无法弄清楚如何使用 BeautifulSoup 做到这一点。我想在没有 API 的情况下执行此操作,因为我将其与代码结合使用以跟踪其他社交媒体平台。有什么建议吗?

最佳答案

使用 API 是最简单的方法,但我也发现了一种非常 hacky 的方法:

import requests

username = "espn"
url = 'https://www.instagram.com/' + username
r = requests.get(url).text

start = '"edge_followed_by":{"count":'
end = '},"followed_by_viewer"'
followers= r[r.find(start)+len(start):r.rfind(end)]

start = '"edge_follow":{"count":'
end = '},"follows_viewer"'
following= r[r.find(start)+len(start):r.rfind(end)]

print(followers, following)

如果您查看请求给出的响应,会发现一行 Javascript 包含真正的关注者数量:

...edge_followed_by":{"count":10770969},"followed_by_viewer":{...

所以我只是通过查找前后的子串来提取数字。

关于python - 网络抓取 Instagram 关注者数量 BeautifulSoup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52225334/

相关文章:

Python-在Python3.3.1中导入BeautifulSoup4失败,但在Python 2.7中成功-使用easy_install安装

python - 图片的 urlretrieve 返回 HTTP 错误 403 : Forbidden

python - 什么时候使用 Django get_absolute_url() 方法?

python字符串替换

python - Pyramid BeforeRender 订阅和访问 .request

python - 如何搜索匹配的字符串,然后提取其后面的字符串和冒号

javascript - 从网页中提取表格

Python Pygame 不会退出

python - 尝试使用 BeautifulSoup 从 Kayak 网站获取 href URL

mapreduce - python - PipeMapRed.waitOutputThreads() : subprocess failed with code 1