【发布时间】:2014-07-31 17:44:44
【问题描述】:
我正在通过 Python Challenge 来学习 Python。在这些挑战中,获取页面源代码可能非常有益。但是,在我的 Windows 机器上使用 Python-Requests 包时,我没有收到预期的页面源代码。
代码:
# Using requests
import requests
url = "http://www.pythonchallenge.com/pc/def/ocr.html"
r = requests.get(url)
print(r.text)
我的回复(为便于阅读而格式化):
<html>
<head>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
</head>
<body>
<script>
*Copyright (c) 2010 John Resig, http://jquery.com/
*Permission is hereby granted, free of charge, to any person obtaininga copy
*of this software and associated documentation files //(the"Software"), to deal
*in the Software without restriction, including without limitation the rights to
* use, copy, modify,\tmerge, //publish,distribute, sublicense, and/or sell copies
*of the Software, and to permit persons to whom the Software is furnished to do so,
*subject //to the following conditions: The above copyright notice and this permission notice shall be included in a
*ll copies or substantial portions of the Software.
var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012
3456789+/=";
function uTF8Encode(string)
{
string = string.replace(/x0dx0a/g, "x0a");
var output = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
output += String.fromCharCode(c);
else if ((c > 127) && (c < 2048)) {
output += String.fromCharCode((c >> 6) | 192);
output += String.fromCharCode((c & 63) | 128);
else {
output += String.fromCharCode((c >> 12) | 224);
output += String.fromCharCode(((c >> 6) & 63) | 128);
output += String.fromCharCode((c & 63) | 128);
}
}
return output;
}
function base64Encode(input)
{
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = uTF8Encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
}
else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + keyString.charAt(enc1) + keyString.charAt(enc2) + keyString.charAt(enc3) + keyString.charAt(enc4);
}
return output;
}
window.top.location.href = 'https://205.159.94.140/connect/Access?AgentCode=000&url=' + base64Encode(window.top.location.href) + '&cti=';
</script>
</body>
</html>
相关页面:http://www.pythonchallenge.com/pc/def/ocr.html
我收到的响应与我使用浏览器检查时收到的来源不匹配。此外,当我在另一台机器(OS X)上运行我的代码时,我可以很好地获取页面源代码。为什么会出现这种情况?
【问题讨论】:
-
首先,排除一些简单的东西:您是否在两台机器上使用相同版本的 Python 和请求?如果你在 Windows 上运行脚本几次,每次都会出错吗?
-
在 linux 上也可以正常工作,你确定你使用的是正确的 url?
-
如何在 Windows 上调用脚本?两台计算机是否在同一个网络上?看起来 Windows 机器正在通过代理或 wifi 网络发出请求,要求您通过(例如)弹出窗口正式加入网络。
-
尝试在 cmd 中的 python shell 中执行此操作
-
@mjk 这可能是问题所在。 Windows 机器通过我的工作网络,而另一台在家里。相同版本的 Python (3.4)。使用 Python Tools for Visual Studio 运行。
标签: python python-3.x python-requests