我为Instagram创建了一个机器人,当它喜欢一个图像时效果很好但是当它评论时,前几个在一组图像中工作,但随后开始评论“无”#39;我不能为我的生活找到错误,并认为两次评论相同的事情是一个问题吗?
这是代码。我知道这是一个巨大的缝隙,但它将开箱即用,并完全复制问题。
import requests
import json
import random
def gen_comment():
comment_list = ["great job!", "lb", "nice shot, take a look at mine!", "perfect!", "#beautiful", "nice shot!", "awesome!", "great photo!", "nice", ":)", "love this", "great shot! take a look at my account! ;)", "WOW!", "lol", "WoW!", 'lovely!', 'amazing']
comment = random.choice(comment_list)
return comment
def comment(media_id):
""" Send http request to comment """
comment_text = gen_comment()
comment_post = {'comment_text': comment_text}
url_comment = 'https://www.instagram.com/web/comments/%s/add/' % (media_id)
try:
comment = s.post(url_comment, data=comment_post)
if comment.status_code == 200:
return comment_text
else:
print comment.status_code
except:
print("error on comment")
def get_media_id_by_tag(tag):
""" Get media ID set, by your hashtag """
url_tag = '%s%s%s' % ('https://www.instagram.com/explore/tags/', tag, '/')
try:
r = s.get(url_tag)
text = r.text
finder_text_start = ('<script type="text/javascript">'
'window._sharedData = ')
finder_text_start_len = len(finder_text_start) - 1
finder_text_end = ';</script>'
all_data_start = text.find(finder_text_start)
all_data_end = text.find(finder_text_end, all_data_start + 1)
json_str = text[(all_data_start + finder_text_start_len + 1) \
: all_data_end]
all_data = json.loads(json_str)
return list(all_data['entry_data']['TagPage'][0]['tag']['media']['nodes'])
except Exception as e:
print("Except on get_media!")
print(e)
username = raw_input("Username: ")
password = raw_input("Password: ")
tag = raw_input("Tag: ")
user_agent = ("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36")
s = requests.Session()
s.cookies.update({'sessionid': '', 'mid': '', 'ig_pr': '1',
'ig_vw': '1920', 'csrftoken': '',
's_network': '', 'ds_user_id': ''})
login_post = {'username': username,
'password': password}
s.headers.update({'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en',
'Connection': 'keep-alive',
'Content-Length': '0',
'Host': 'www.instagram.com',
'Origin': 'https://www.instagram.com',
'Referer': 'https://www.instagram.com/',
'User-Agent': user_agent,
'X-Instagram-AJAX': '1',
'X-Requested-With': 'XMLHttpRequest'})
r = s.get('https://www.instagram.com/')
s.headers.update({'X-CSRFToken': r.cookies['csrftoken']})
login = s.post('https://www.instagram.com/accounts/login/ajax/', data=login_post,
allow_redirects=True)
s.headers.update({'X-CSRFToken': login.cookies['csrftoken']})
csrftoken = login.cookies['csrftoken']
media = get_media_id_by_tag(tag)
for i in media:
c = comment(i['id'])
print 'commented {} on media {}'.format(c, i['id'])
编辑1 我编辑了我的代码,发现我在评论函数上遇到400错误,该函数停止返回所需文本的函数。我不知道为什么我会收到400错误,但我会研究它。任何帮助表示赞赏