我遇到一个问题,我可以在Firefox,Chrome甚至Java中打开的页面无法使用urllib2在Python中打开:
import urllib2
sock = urllib2.urlopen('http://www.example.com')
li = sock.read()
sock.close()
print li
此代码失败(对于我尝试加载的特定公司网页)。该页面实际上是一个复杂的后端服务器的接口,我们得到的响应只是几行(不正确的)文本。起初我们认为有一些bot过滤,但我们确实使用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会导致此代码失败的原因是什么?是否有另一种方法可以加载可能有用的页面?