Python urllib2无法打开web pag

2024-10-03 19:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,我可以在Firefox、Chrome甚至Java中打开的页面无法在Python中使用urllib2打开:

import urllib2
sock = urllib2.urlopen('http://www.example.com')
li = sock.read()
sock.close()
print li

此代码失败(对于我尝试加载的特定公司网页)。该页面实际上是一个复杂后端服务器的接口,我们得到的响应只是几行(不正确的)文本。一开始我们以为有一些机器人过滤正在进行,但我们确实使用Java加载了页面:

package com.ebay.marketing.rtm.components.impl.selector;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class RtmApiCheck {

    private static Client mClient;

    private void initClient() {
        Client client = mClient;
        if (client == null) {
            synchronized (this) {
                client = mClient;
                if (client == null) {
                    mClient = client = Client.create();

                }
            }
        }
    }

    public static void main(String[] args) {
        RtmApiCheck check = new RtmApiCheck();
        try {
            check.initClient();
            for(int i=0;i<100;i++) {
                WebResource wr = mClient.resource("http://www.example.com");
                ClientResponse result = wr.get(ClientResponse.class);
                String strResult = result.getEntity(String.class);
                System.out.println(strResult);
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Python到底发生了什么导致这段代码失败?是否有其他方法可以加载页面?你知道吗


Tags: importcomclientapistring页面urllib2class