Unable to follow a user in a website using some script built upon requests

只谈情不闲聊 提交于 2020-06-29 03:40:18

问题


I'm trying to follow a user in Instagram using the script below built upon requests. The script can log me in successfully but it can't help me follow that user. I tried my best to mimic the process through the script what I could see in dev tools while following that user manually.

User that I wish to follow using the script.

This is how the result will look like when the script will work.

I've tried with:

import re
import requests
from bs4 import BeautifulSoup
from datetime import datetime

target_link = 'https://www.instagram.com/p/CBySO76FgD6/'
profile_link = 'https://www.instagram.com/{}/'
start_link = 'https://www.instagram.com/accounts/login/'
login_url = 'https://www.instagram.com/accounts/login/ajax/'
follow_url = 'https://www.instagram.com/web/friendships/{}/follow/'

username = "instagram_username"
password = "instagram_password"

timeval = int(datetime.now().timestamp())

payload = {
    'username': username,
    'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{timeval}:{password}',
    'queryParams': {},
    'optIntoOneTap': 'false'
}

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
    r = s.get(start_link)
    s.headers['x-csrftoken'] = re.findall(r"csrf_token\":\"(.*?)\"",r.text)[0]
    r = s.post(login_url,data=payload) #it does log me in flawlessly
    # print(r.text)
    s.get(profile_link.format(username)) #send this requests only to get cookies from profile page
    r = s.get(target_link)
    follow_id = re.findall(r'viewer_can_reshare[\s\S]+?id\":\"(.*?)\"',r.text)[0]
    r = s.post(follow_url.format(follow_id),data=None)
    print(r.status_code) #giving 403 status code

回答1:


To make such request working you have to change some headers. the headers should look like this:

'cookie': 'sessionid={}%3ADYLfeCKlCulTTJ%3A6;'.format(login_id),
'origin': 'https://www.instagram.com',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) \
                 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
'x-csrftoken': 'rf3krAvciHRvjSBoqP4NYVXmw1wP8rEO',
'x-instagram-ajax': '846d5a59d9e9'

where login_id - it's id of your user. NOTE, not username, it should be numeric id (ex. 8780495634) then you can make post request to follow ant user you want.



来源:https://stackoverflow.com/questions/62600063/unable-to-follow-a-user-in-a-website-using-some-script-built-upon-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!