0

私の質問をむき出しにする前に、いくつかのコンテキストが必要です。GETHTTPとリクエストを Web サイトに発行しようとしてPOSTいますが、次の注意事項があります。

  • リダイレクトが予想される
  • クッキーが必要です
  • リクエストは SOCKS プロキシ (v4a) を通過する必要があります

これまでは、twisted.web.client.Agentサブクラス (例: BrowserLikeRedirectAgent) を使用していましたが、残念ながら、SOCKS プロキシはまだサポートされていないようです (ProxyAgentこのクラスは HTTP プロキシ用であるため、使用できません)。

私はツイストソックスに出くわしました。これは私がやりたいことをできるように見えますが、それがエージェントの代わりに使用されていることに気付きましHttpClientFactoryHttpClientFactoryAgent

以下は、ツイスト ソックスを使用したサンプル コードです。追加の質問が 2 つあります。

  1. この例で Cookie を使用するにはどうすればよいですか? adictと acookielib.CookieJarインスタンスをHttpClientFactorycookieskwarg に渡そうとしましたが、これによりエラーが発生します (文字列に関する何かが期待されています...どうすれば Cookie を文字列として送信できますか?)

  2. このコードをリファクタリングして使用できますAgentか? Agent念頭に置いて書かれたかなり大きなコードベースが既にあるので、これは理想的です。

```

import sys
from urlparse import urlparse
from twisted.internet import reactor, endpoints
from socksclient import SOCKSv4ClientProtocol, SOCKSWrapper
from twisted.web import client

class mything:
    def __init__(self):
        self.npages = 0
        self.timestamps = {}

    def wrappercb(self, proxy):
        print "connected to proxy", proxy

    def clientcb(self, content):
        print "ok, got: %s" % content[:120]
        print "timetamps " + repr(self.timestamps)
        self.npages -= 1
        if self.npages == 0:
            reactor.stop()

    def sockswrapper(self, proxy, url):
        dest = urlparse(url)
        assert dest.port is not None, 'Must specify port number.'
        endpoint = endpoints.TCP4ClientEndpoint(reactor, dest.hostname, dest.port)
        return SOCKSWrapper(reactor, proxy[1], proxy[2], endpoint, self.timestamps)

def main():
    thing = mything()

    # Mandatory first argument is a URL to fetch over Tor (or whatever
    # SOCKS proxy that is running on localhost:9050).
    url = sys.argv[1]
    proxy = (None, 'localhost', 9050, True, None, None)

    f = client.HTTPClientFactory(url)
    f.deferred.addCallback(thing.clientcb)
    sw = thing.sockswrapper(proxy, url)
    d = sw.connect(f)
    d.addCallback(thing.wrappercb)
    thing.npages += 1

    reactor.run()

if '__main__' == __name__:
    main()

```

4

1 に答える 1