python实现Instagram网络爬虫
作者:互联网
python实现Instagram网络爬虫
instagram爬虫
背景介绍
Instagram是国际最大的社交媒体之一。这是一个巨大地相片分享社区群,全世界的网民们可以在Instagram上以快速,出色以及有趣的方式来与朋友分享照片,分享生活,实现信息的即时分享、传播互动。
利用python语言从账户内获取到其个人基本信息:用户简介、发帖数、关注数、被关注数以及发布的图片信息:图片文件、发布时间、点赞数、评论数。通过数据筛选,将信息保存到数据库中,并对这些数据进行相应的处理与分析。
爬虫的设计思路
1.首先确定要爬取的网页URL地址
2.通过HTTP/HTTPS协议来获取对于的HTML页面
3.提取HTML里面有用的数据
4.如果是有用的数据,那么就保存起来,如果是页面里有其他URL,那么就继续执行第二步
大致实现步骤
1.设置代理服务,成功访问Instagram页面
2.利用python,对特定用户“Instagram”的follower进行爬取,数量为10000
3.对这些用户个人信息,发布的图片内容以及对应的点赞和评论数量进行爬取
4.结果存入数据库,并对采集的数据做基本的分析统计
代码
导入包
import pandas as pd
import traceback
import random
import os
import re
import sys
import json
import time
import random
import requests
import pymongo
from pyquery import PyQuery as pq
链接 mongo 数据库
client = pymongo.MongoClient(host="localhost",port=27017)
db = client['instagram']
table_user = db['user']
table_post = db['post']
url_base = 'https://www.instagram.com/{}/'
uri = 'https://www.instagram.com/graphql/query/?query_hash=a5164aed103f24b03e7b7747a2d94e3c&variables=%7B%22id%22%3A%22{user_id}%22%2C%22first%22%3A12%2C%22after%22%3A%22{cursor}%22%7D'
vpn 端口
proxies = {
'http': 'http://127.0.0.1:11000',
'https': 'http://127.0.0.1:11000',
}
headers = {
'authority': 'www.instagram.com',
'method': 'GET',
'path': '/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=%7B%22id%22%3A%221507979106%22%2C%22include_reel%22%3Atrue%2C%22fetch_mutual%22%3Atrue%2C%22first%22%3A24%7D',
'scheme': 'https',
'cookie': 'mid=XFZ8GwALAAGT7q5EpO0c2fInHptQ; mcd=3; ds_user_id=5908418817; ig_did=85FF1DEF-2EFC-4878-BE84-B1C8BE6CE8BD; ig_cb=1; fbm_124024574287414=base_domain=.instagram.com; csrftoken=xPM4ERPXxmLCIPwHLSqYh5kzSXqqZCkL; sessionid=5908418817%3A7v38AuQX9lztEW%3A4; shbid=10185; shbts=1584248837.7816854; rur=ASH; urlgen="{\"94.190.208.156\": 4760}:1jDLb7:htq8GLniOckdSATmm3SUTWBuN3o"',
'referer': 'https://www.instagram.com/skuukzky/followers/?hl=zh-cn',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
'x-csrftoken': 'xPM4ERPXxmLCIPwHLSqYh5kzSXqqZCkL',
'x-ig-app-id': '936619743392459',
'x-ig-www-claim': 'hmac.AR2iHSXFdGL67VxTW3jLLPH5WiFoUjzDxhEbyxgHYhXH5Y4x',
'x-requested-with': 'XMLHttpRequest',
}
请求网页源代码
def get_html(url):
try:
response = requests.get(url, headers=headers, proxies=proxies)
if response.status_code == 200:
return response.text
else:
print('请求网页源代码错误, 错误状态码:', response.status_code)
except Exception as e:
print(e)
return None
请求网页json
def get_json(url):
try:
response = requests.get(url, headers=headers, timeout=10, proxies=proxies)
if response.status_code == 200:
return response.json()
else:
print('请求网页json错误, 错误状态码:', response.status_code)
except Exception as e:
print(e)
time.sleep(60 + float(random.randint(1, 4000))/100)
return get_json(url)
请求连接
def get_content(url):
try:
response = requests.get(url, headers=headers, timeout=10, proxies=proxies)
if response.status_code == 200:
return response.content
else:
print('请求照片二进制流错误, 错误状态码:', response.status_code)
except Exception as e:
print(e)
return None
爬取网页具体内容
def get_urls(html):
id, username = '', ''
user_id = re.findall('"profilePage_([0-9]+)"', html, re.S)[0]
print('user_id:' + user_id)
doc = pq(html)
items = doc('script[type="text/javascript"]').items()
for item in items:
if item.text().strip().startswith('window._sharedData'):
print(111)
js_data = json.loads(item.text()[21:-1], encoding='utf-8')
user = js_data["entry_data"]["ProfilePage"][0]["graphql"]["user"]
id = user['id']
username = user['username']
fullname = user['full_name']
intro = user['biography']
following_count = user['edge_follow']['count']
followed_count = user['edge_followed_by']['count']
post_count = user['edge_owner_to_timeline_media']['count']
table_user.update_one({'id': id}, {'$set': {
'id':id,
'username':username,
'fullname':fullname,
'intro':intro,
'following_count':following_count,
'followed_count':followed_count,
'post_count':post_count
}}, True)
# print(js_data)
# time.sleep(1000)
edges = js_data["entry_data"]["ProfilePage"][0]["graphql"]["user"]["edge_owner_to_timeline_media"]["edges"]
page_info = js_data["entry_data"]["ProfilePage"][0]["graphql"]["user"]["edge_owner_to_timeline_media"]['page_info']
cursor = page_info['end_cursor']
flag = page_info['has_next_page']
for edge in edges:
post_id = edge['node']['id']
post_time = edge['node']['taken_at_timestamp']
post_time = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(post_time))
comment_count = edge['node']['edge_media_to_comment']['count']
like_count = edge['node']['edge_media_preview_like']['count']
urls = []
if edge['node']['display_url']:
display_url = edge['node']['display_url']
print(display_url)
urls.append(display_url)
urls = ';'.join(urls)
table_post.update_one({'post_id': post_id}, {'$set': {
'user_id': id,
'user_name':username,
'post_id':post_id,
'time': post_time,
'comment_count': comment_count,
'like_count': like_count,
'img_urls': urls
}}, True)
print({
'user_id': id,
'user_name': username,
'post_id': post_id,
'time': post_time,
'comment_count': comment_count,
'like_count': like_count,
'img_urls': urls
})
# print(cursor, flag)
while flag:
url = uri.format(user_id=user_id, cursor=cursor)
js_data = get_json(url)
infos = js_data['data']['user']['edge_owner_to_timeline_media']['edges']
cursor = js_data['data']['user']['edge_owner_to_timeline_media']['page_info']['end_cursor']
flag = js_data['data']['user']['edge_owner_to_timeline_media']['page_info']['has_next_page']
for edge in infos:
# print('\n\n\n\n',edge)
post_id = edge['node']['id']
post_time = edge['node']['taken_at_timestamp']
post_time = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(post_time))
comment_count = edge['node']['edge_media_to_comment']['count']
like_count = edge['node']['edge_media_preview_like']['count']
urls = []
if edge['node']['is_video']:
video_url = edge['node']['video_url']
if video_url:
print(video_url)
# urls.append(video_url)
else:
if edge['node']['display_url']:
display_url = edge['node']['display_url']
print(display_url)
urls.append(display_url)
urls = ';'.join(urls)
table_post.update_one({'post_id': post_id}, {'$set': {
'user_id': id,
'user_name': username,
'post_id': post_id,
'time': post_time,
'comment_count': comment_count,
'like_count': like_count,
'img_urls': urls
}}, True)
print({
'user_id': id,
'user_name': username,
'post_id': post_id,
'time': post_time,
'comment_count': comment_count,
'like_count': like_count,
'img_urls': urls
})
主函数
def main(user):
get_urls(get_html(url_base.format(user)))
if __name__ == '__main__':
df = pd.read_csv('source.csv')
for index, row in df.iterrows():
print('{}/{}'.format(index, df.shape[0]), row['username'])
if row['isFinished']>0:
continue
user_name = row['username']
try:
start = time.time()
main(user_name)
end = time.time()
spent = end - start
print('spent {} s'.format(spent))
df.loc[index, 'isFinished'] = 1
df.to_csv('source.csv', index=False, encoding='utf-8-sig')
time.sleep(random.randint(2,3))
except Exception as e:
# if isinstance(e, IndexError) or isinstance(e, TypeError):
if isinstance(e, IndexError):
print('{} 改名了'.format(user_name))
df.loc[index, 'isFinished'] = 2
df.to_csv('source.csv', index=False, encoding='utf-8-sig')
continue
print(traceback.format_exc())
break
数据展示
账户个人基本信息
包含了账户id、用户名、用户简介、关注数、被关注数、发帖数。
发布的图片信息
包含了账户id、用户名、图片文件、发布时间、点赞数、评论数
数据简要分析
由此可以推断出我们爬取的用户大多数多为新用户(其中也可能有活跃性低的用户)
在爬取的对象中存在着局限性。
标签:count,Instagram,python,爬虫,url,edge,user,post,id 来源: https://blog.csdn.net/jlycd/article/details/113245164