3

を使用してWebページにアクセスする必要があります

twisted.web.client.getPage()

または、既知のアドレス (例: www.google.com) から Web ページをダウンロードする同様の方法を使用する場合、問題は次のとおりです。私はプロキシ サーバーの背後にいて、twisted または factory を構成して自分のプロキシ、アイデアはありますか?

ユーザー、パスワード、ホスト、およびポートを指定する必要があることに注意してください。私のLinuxマシンでセットアップhttp_proxyhttps_proxyhttp://user:pwd@ip:port

前もって感謝します。

4

4 に答える 4

3
from twisted.internet import reactor
from twisted.web import client

def processResult(page):
    print "I got some data", repr(page)
    reactor.callLater(0.1, reactor.stop)
def dealWithError(err):
    print err.getErrorMessage()
    reactor.callLater(0.1, reactor.stop)

class ProxyClientFactory(client.HTTPClientFactory):
    def setURL(self, url):
        client.HTTPClientFactory.setURL(self, url)
        self.path = url

factory = ProxyClientFactory('http://url_you_want')
factory.deferred.addCallbacks(processResult, dealWithError)

reactor.connectTCP('proxy_address', 3142, factory)
reactor.run()
于 2009-10-31T01:37:57.353 に答える
1

ここでは認証リクエストのサンプルコードが機能しなかったため、基本認証を使用して同様のことを行う必要がありました。これは機能するバージョンです。

import base64

from twisted.internet import defer, reactor
from twisted.web import client, error, http

from ubuntuone.devtools.testcases.squid import SquidTestCase

# ignore common twisted lint errors
# pylint: disable=C0103, W0212


class ProxyClientFactory(client.HTTPClientFactory):
    """Factory that supports proxy."""

    def __init__(self, proxy_url, proxy_port, url, headers=None):
        self.proxy_url = proxy_url
        self.proxy_port = proxy_port
        client.HTTPClientFactory.__init__(self, url, headers=headers)

    def setURL(self, url):
        self.host = self.proxy_url
        self.port = self.proxy_port
        self.url = url
        self.path = url


class ProxyWebClient(object):
    """Provide useful web methods with proxy."""

    def __init__(self, proxy_url=None, proxy_port=None, username=None,
            password=None):
        """Create a new instance with the proxy settings."""
        self.proxy_url = proxy_url
        self.proxy_port = proxy_port
        self.username = username
        self.password = password

    def _process_auth_error(self, failure, url, contextFactory):
        """Process an auth failure."""
        # we try to get the page using the basic auth
        failure.trap(error.Error)
        if failure.value.status == str(http.PROXY_AUTH_REQUIRED):
            auth = base64.b64encode('%s:%s' % (self.username, self.password))
            auth_header = 'Basic ' + auth.strip()
            factory = ProxyClientFactory(self.proxy_url, self.proxy_port, url,
                    headers={'Proxy-Authorization': auth_header})
            # pylint: disable=E1101
            reactor.connectTCP(self.proxy_url, self.proxy_port, factory)
            # pylint: enable=E1101
            return factory.deferred
        else:
            return failure

    def get_page(self, url, contextFactory=None, *args, **kwargs):
        """Download a webpage as a string.

        This method relies on the twisted.web.client.getPage but adds and extra
        step. If there is an auth error the method will perform a second try
        so that the username and password are used.
        """
        scheme, _, _, _ = client._parse(url)
        factory = ProxyClientFactory(self.proxy_url, self.proxy_port, url)
        if scheme == 'https':
            from twisted.internet import ssl
            if contextFactory is None:
                contextFactory = ssl.ClientContextFactory()
            # pylint: disable=E1101
            reactor.connectSSL(self.proxy_url, self.proxy_port,
                               factory, contextFactory)
            # pylint: enable=E1101
        else:
            # pylint: disable=E1101
            reactor.connectTCP(self.proxy_url, self.proxy_port, factory)
            # pylint: enable=E1101
        factory.deferred.addErrback(self._process_auth_error, url,
                                    contextFactory)
        return factory.deferred
于 2011-12-15T16:35:45.483 に答える
1

nosklo のソリューションを機能させるには、認証が必要であることを示す「401」用の別のハンドラーを作成する必要があります。このようなことを試してください

def checkAuthError(self,failure,url):
    failure.trap(error.Error)
    if failure.value.status == '401':
        username = raw_input("User name: ")
        password = getpass.getpass("Password: ")
        auth = base64.encodestring("%s:%s" %(username, password))
        header = "Basic " + auth.strip()
        return client.getPage(
            url, headers={"Authorization": header})
    else:
        return failure

これにより、オペレーターはコマンドラインで情報を提供するように求められます。または、選択した別の方法でユーザー名とパスワードを提供することもできます。コールバックであっても、他のハンドラーが追加される前に、これがエラーバックとして追加される最初のハンドラーであることを確認してください。これには、さらにいくつかのインポートも必要です。コマンド ライン プロンプトを操作するための「base64」、「g​​etpass」、および「error」。

于 2009-11-09T03:19:24.680 に答える
0

http_proxy環境変数を使用することにしました。リダイレクトが常に取得されるとは限らない、または正しい方法で取得されるという問題がありました。とは言え、noskloさんの対応は本当に助かりました!

import os
from twisted.web import client

class ProxyClientFactory(client.HTTPClientFactory):
    def setURL(self, url):
        '''More sensitive to redirects that can happen, that
        may or may not be proxied / have different proxy settings.'''
        scheme, host, port, path = client._parse(url)
        proxy = os.environ.get('%s_proxy' % scheme)
        if proxy:
            scheme, host, port, path = client._parse(proxy)
            self.scheme = scheme
            self.host = host
            self.port = port
            self.path = url
            self.url = url
        else:
            client.HTTPClientFactory.setURL(self, url)

factory = ProxyClientFactory(url)
# Callback configuration
# If http_proxy or https_proxy, or whatever appropriate proxy
# is set, then we should try to honor that. We do so simply 
# by overriding the host/port we'll connect to. The client
# factory, BaseRequestServicer takes care of the rest
scheme, host, port, path = client._parse(url)
proxy = os.environ.get('%s_proxy' % scheme)
if proxy:
    scheme, host, port, path = client._parse(proxy)
reactor.connectTCP(host, port, factory)
于 2011-11-04T16:20:37.267 に答える