首页 > 解决方案 > 使用python从Instagram收集用户信息

问题描述

我目前正在使用 python 从 instagram 上的用户那里收集信息,使用包含 instagram 用户链接的文本文件。虽然我可以收集关注者的数量、关注的数量和帖子的数量,但我希望能够从用户那里收集生物信息。收集生物信息将使我最终能够解析这些信息并收集电子邮件。我能做到这一点的最好和最简单的方法是什么?

我在 Python 方面没有经验,所以我从互联网上获取了一个示例代码。我试图分析代码并使用我所知道的来修改它以满足我的需要,但没有结果。

import requests
import urllib.request
import urllib.parse
import urllib.error
from bs4 import BeautifulSoup
import ssl
import json


class Insta_Info_Scraper:

    def getinfo(self, url):
        html = urllib.request.urlopen(url, context=self.ctx).read()
        soup = BeautifulSoup(html, 'html.parser')
        data = soup.find_all('meta', attrs= {'property':'og:description'})
        text = data[0].get('content').split()
        user = '%s %s %s' % (text[-3], text[-2], text[-1])
        followers = text[0]
        following = text[2]
        posts = text[4]
        email = ""
        print ('User:', user)
        print ('Followers:', followers)
        print ('Following:', following)
        print ('Posts:', posts)
        print ('Email:', email)
        print ('---------------------------')

    def main(self):
        self.ctx = ssl.create_default_context()
        self.ctx.check_hostname = False
        self.ctx.verify_mode = ssl.CERT_NONE

        with open('users.txt') as f:
            self.content = f.readlines()
        self.content = [x.strip() for x in self.content]
        for url in self.content:
            self.getinfo(url)


if __name__ == '__main__':
    obj = Insta_Info_Scraper()
    obj.main()

目前,我将一个空字符串作为“电子邮件”变量的值,但最终希望将其替换为能够从特定用户那里获取电子邮件的代码。

标签: pythonbeautifulsoupinstagramscreen-scraping

解决方案


访问 Instagram 的公共数据结构的便捷工具是Instaloader,这是一个 Python 包,它提供 Python 模块和 CLI 来访问 Instagram。完成pip install instaloader安装后,您可以轻松获取保存在 JSON 文件中的配置文件元数据

instaloader --no-posts --no-profile-pic --no-compress-json profile1 [profile2 ...]

然后你可以使用jq,“一个轻量级和灵活的命令行 JSON 处理器”,来提取刚刚保存的信息,例如下面的命令打印 profile1 的传记:

jq -r .node.biography profile1/profile1_*.json

同样,一种不让 Python 访问相同信息的方法:

import instaloader
L = instaloader.Instaloader()
profile = instaloader.Profile.from_username(L.context, 'profile1')
print(profile.biography)

推荐阅读