我刚刚开始学习如何使用 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/