2012-02-13 3 views
3

이전 코드는 나에게이 URL을 제공합니다 : http://en.wikipedia.org/wiki/M%C3%BCnster. 지금, 나는 그것을 요청하고 싶습니다,하지만 그것을 할 수있는 방법을 알아낼 수 없습니다 :이미 인용 된 URL을 요청하는 방법은 무엇입니까?

>>> requests.get('http://en.wikipedia.org/wiki/M%C3%BCnster') 
<Response [400]> 
>>> requests.get(urlparse.unquote('http://en.wikipedia.org/wiki/M%C3%BCnster')) 
<Response [400]> 
>>> requests.get(urlparse.unquote('http://en.wikipedia.org/wiki/M%C3%BCnster').decode('utf-8')) 
<Response [400]> 

문제는 요청이 인용에 대해 지나치게 현명하게하려고 실제로 요청된다는 점이다 :

Request URI: /wiki/M%25C3%25BCnster 
Request URI: /wiki/M%25C3%25BCnster 
Request URI: /wiki/M%25C3%25BCnster 

아이디어가 있으십니까? .decode('utf-8') 추가

+0

urllib 또는 urllib2와 함께 작동하지 않지만 대신 오류 403을 제공합니다 ... – lRem

+0

urllib *의 문제는 요청 문제와 관련이없는 위키 피 디아 서버에 의해 위태롭게 된 것 같습니다. – lRem

+0

'요청 '이란 무엇입니까? – maciej

답변

1

시도 : 사용자 정의 사용자 에이전트 헤더

requests.get(urlparse.unquote('http://en.wikipedia.org/wiki/M%C3%BCnster').decode('utf-8')) 
+0

아니, 나를 위해 작동하지 않습니다. 위의 설명에 추가했습니다. – lRem

2

간단한 urlparse.unquote 일을 할 것으로 보인다.

>>> s = 'http://en.wikipedia.org/wiki/M%C3%BCnster' 
>>> import urllib2, urlparse 
>>> headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; rv:9.0.1) Gecko/20100101 Firefox/9.0.1'} 
>>> url = urlparse.unquote(s) 
>>> req = urllib2.Request(url, None, headers) 
>>> resp = urllib2.urlopen(req) 
>>> print resp.code 
200 
>>> data = resp.read() 
>>> print 'The last outstanding palace of the German baroque period is created according to plans by Johann Conrad Schlaun.' in data 
True 

유니 코드 객체로 바이트 문자열을 디코딩하지 마십시오, 그것은 urlopen에 UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 11: ordinal not in range(128)됩니다.

+0

니스. 그러나 요청을 사용한 솔루션을 원했습니다. 그것은 urllib과는 다른 라이브러리입니다. 정말 좋지만, 이것을 해결할 수 없다면 urllib로 되돌릴 필요가 있습니다 : / – lRem

관련 문제