2013-03-09 4 views
2

저는 파이썬에 아주 익숙합니다. 이제 며칠 동안 urllib2로 쿠키를 보내려고합니다.urllib2 python을 통해 쿠키 보내기/설정

list_type=height 

가 .. 기본적으로 특정 순서에 따라 페이지의 목록을 정렬하는 : 그래서, 기본적으로 내가 얻고 싶은 페이지에, 나는처럼 보이는 "전송 쿠키"가 있음을 불을 지르고에서 참조하십시오.

class Networksx(object): 
    def __init__(self): 
     self.cj = cookielib.CookieJar() 
     self.opener = urllib2.build_opener\ 
       #socks handler 
     self.opener.addheaders = [ 
     ('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13'), 
     ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'), 
     ('Keep-Alive', '115'), 
     ('Connection', 'keep-alive'), 
     ('Cache-Control', 'max-age=0'), 
     ('Referer', 'http://www.google.com'), 
     ("Cookie", {"list_type":"height"}), 
    ] 
    urllib2.install_opener(self.opener) 
    self.params = { 'Set-Cookie': "list_type":"height"} 
    self.encoded_params = urllib.urlencode(self.params) 

    def fullinfo(self,url): 
     return self.opener.open(url,self.encoded_params).read() 

: -

내가 렌더링 된 페이지가 발효 설정 이상이 taked 있도록 urllib2를 통해이 위의 쿠키 정보를 보내려고 여기가 내가 만들어 쓰기를 시도하고 코드 작동입니다 쿠키 설정

  • 헤더
  • 를 통해 매개 변수를 설정 : 당신이 볼 수 ..as, 나는 몇 가지를 시도했다

    그러나 이것들은 내가 원하는대로 특정 list_order (높이)의 페이지를 렌더링하는 것처럼 보이지 않습니다. 누군가가 urllib2와 함께 쿠키 정보를 보내는 방법과 관련하여 올바른 방향으로 나를 지적 할 수 있는지 궁금합니다.

    감사합니다.

답변

5

cookie.txt을 생성하는 쉬운 방법이 크롬 확장 기능입니다 참조 : 나는 붙여 넣기가에서

죄송합니다 [업데이트]

https://chrome.google.com/webstore/detail/cookietxt-export/lopabhfecdfhgogdbojmaicoicjekelh

import urllib2, cookielib 

url = 'https://example.com/path/default.aspx' 
txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} 

cj = cookielib.LWPCookieJar() 
# cj.load signature: filename=None, ignore_discard=False, ignore_expires=False 
cj.load('/path/to/my/cookies.txt') 

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
urllib2.install_opener(opener) 

req = urllib2.Request(url, None, txheaders) 
handle = urllib2.urlopen(req) 
했다 오래된 코드 스 니펫을 오랫동안 잊어 버렸습니다. LWPCookieJar 문서 문자열에서 :

The LWPCookieJar saves a sequence of "Set-Cookie3" lines. "Set-Cookie3" is the format used by the libwww-perl libary, not known to be compatible with any browser, but which is easy to read and doesn't lose information about RFC 2965 cookies.

따라서 최신 브라우저에서 생성 된 cookie.txt와 호환되지 않습니다. 당신이 그것을로드하려고하면 : LoadError: 'cookies.txt' does not look like a Set-Cookie3 (LWP) format file 얻을 것이다.

there is something wrong with the format of the output from chrome extension. I just googled the lwp problem and found: code.activestate.com/recipes/302930-cookielib-example the code spits out the cookie in lwp format and then I follow your steps as it is. - James W

당신은이 Firefox addon하고 "도구 -> 내보내기 쿠키"를 사용할 수 있습니다

당신은 파일을 영업 이익으로 수행하고 변환 할 수 있습니다. cookies.txt 파일의 첫 번째 행이 "# Netscape HTTP Cookie File"이고 다음을 사용하십시오 :

cj = cookielib.MozillaCookieJar('/path/to/my/cookies.txt') 
cj.load() 
+0

안녕하세요 : 도와 줘서 고마워. 나는 지금 막 시도했다 : 그러나, 나는 놓는 것을 보인다 : cookielib.LoadError : 'cookies.txt'는 Set-Cookie3 (LWP) 체재 파일 같이 보이지 않는다. 인터넷 검색은 아무것도 생성하지 않는다 : ( – AJW

+0

고맙다! 그것은 지금 작동한다 ..성가신 문제에 대한 좋은 해결책 :) – AJW

+0

@JamesW : 나는 그것이 효과가있어 기쁘다. 기록을 위해, 처음 시도했을 때 왜 효과가 없었던 것입니까? :-) –

0

저수준 urllib 모듈을 사용하는 것보다 훨씬 쉽게 접근 할 수있는 Python 용 '요청'모듈을 살펴 보는 것이 좋습니다.

http://docs.python-requests.org/en/latest/user/quickstart/#cookies

+0

은 현재 설정에서 가능하지 않습니까? 이 클래스는 꽤 ​​많은 곳에서 재사용됩니다 - 가능하다면 이것을 (urllib2/urllib) 동일하게하고 싶습니다 .. – AJW

+0

'cookielib.LWPCookieJar()'를 보았으나'cookielib.Cookie' 객체는 16 '__init__'에있는 매개 변수들. 무서운. –

+0

코드를 다시 작성하는 것은 쉬워야합니다 .... –