urllib2 HTTP error 429

那年仲夏 提交于 2019-11-30 07:10:32

From https://github.com/reddit/reddit/wiki/API:

Many default User-Agents (like "Python/urllib" or "Java") are drastically limited to encourage unique and descriptive user-agent strings.

This applies to regular requests as well. You need to supply your own user agent header when making the request.

#TODO: change user agent string
hdr = { 'User-Agent' : 'super happy flair bot by /u/spladug' }
req = urllib2.Request(url, headers=hdr)
html = urllib2.urlopen(req).read()

However, this will create a new connection for every request. I suggest using another library that is capable of re-using connections, httplib or Request, for example. It will put less stress on the server and speed up the requests:

import httplib
import time

lst = """
science
scifi
"""

hdr= { 'User-Agent' : 'super happy flair bot by /u/spladug' }
conn = httplib.HTTPConnection('www.reddit.com')
for name in lst.split():
    conn.request('GET', '/r/'+name, headers=hdr)
    print conn.getresponse().read()
    time.sleep(2)
conn.close()
bboe

reddit performs rate limiting by request (not connection as suggested by Anonymous Coward) for both IP addresses and user agents. The issue you are running into is that everyone who attempts to access reddit using urllib2 will be rate limited as a single user.

The solution is to set a user agent which you can find an answer in this question.

Alternatively, forgo writing your own code to crawl reddit and use PRAW instead. It supports almost all the features of reddit's API and you needn't worry about following any of the API rules as it takes care of that for you.

I ran into the same error.changing the code from ``from urllib.request import urlopen from bs4 import BeautifulSoup

html = urlopen(url) bsObj = BeautifulSoup(html) to from urllib.request import urlopen from bs4 import BeautifulSoup import urllib.request

webRequest = urllib.request.Request(url, headers={"User-Agent": }) html = urlopen(webRequest) bsObj = BeautifulSoup(html)``

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