403禁止使用Urllib2 [Python]

url = 'https://www.instagram.com/accounts/login/ajax/'
values = {'username' : 'User',
          'password' : 'Pass'}

#'User-agent', ''
data = urllib.urlencode(values)
req = urllib2.Request(url, data,headers={'User-Agent' : "Mozilla/5.0"}) 
con = urllib2.urlopen( req )
the_page = response.read()

有没有人对此有任何想法?我一直收到错误“403禁止”.
它可能的instagram有一些东西不允许我通过python连接(我不想通过他们的API连接).到底发生了什么,有没有人有任何想法?

谢谢!

编辑:添加更多信息.

我得到的错误就是这个

This page could not be loaded. If you have cookies disabled in your browser, or you are browsing in Private Mode, please try enabling cookies or turning off Private Mode, and then retrying your action.

我编辑了我的代码,但仍然遇到了这个错误.

jar = cookielib.FileCookieJar("cookies")
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
print len(jar) #prints 0
opener.addheaders = [('User-agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36')]
result = opener.open('https://www.instagram.com')
print result.getcode(), len(jar) #prints 200 and 2

url = 'https://www.instagram.com/accounts/login/ajax/'
values = {'username' : 'username',
          'password' : 'password'}

data = urllib.urlencode(values)

response = opener.open(url, data)
print response.getcode()

最佳答案 两个重要的事情,对于初学者:

>确保你保持合法的一面.根据Instagram的Terms of Use

We prohibit crawling, scraping, caching or otherwise accessing any content on the Service via automated means, including but not limited to, user profiles and photos (except as may be the result of standard search engine protocols or technologies used by a search engine with Instagram’s express consent).

You must not create accounts with the Service through unauthorized means, including but not limited to, by using an automated device, script, bot, spider, crawler or scraper.

>有一个Instagram API将有助于保持合法的一面,让生活更轻松.有一个Python客户端:python-instagram

除此之外,Instagram本身是javascript很重,你可能会发现使用urllib2或请求很难.如果出于某种原因,您无法使用API​​,则可以通过selenium查看浏览器自动化.请注意,您也可以自动执行PhantomJS之类的无头浏览器.以下是登录的示例代码:

from selenium import webdriver

USERNAME = "username"
PASSWORD = "password"

driver = webdriver.PhantomJS()
driver.get("https://www.instagram.com")

driver.find_element_by_name("username").send_keys(USERNAME)
driver.find_element_by_name("password").send_keys(PASSWORD)

driver.find_element_by_xpath("//button[. = 'Log in']").click()
点赞