我从yahoo finance解析了源代码,我在读取数据方面没有任何问题。我使用了这种静态方法:
public static String readYahooHtml(String symbol) {
In page = new In("http://finance.yahoo.com/quote/" + symbol);
String html = page.readAll();
if (html.contains("<title></title>")) return null;
else return html;
}
页面示例https://finance.yahoo.com/quote/AES
当我尝试对gurufocus的源代码执行相同的操作时
// Given symbol, get HTML
public static String readGuruFocusHtml(String symbol) {
In page = new In("http://www.gurufocus.com/stock/" + symbol);
String htmlGF = page.readAll();
if (htmlGF.contains("<title></title>")) return null;
else return htmlGF;
}
我得到以下异常:
线程“main”中的异常java.lang.IllegalArgumentException:无法打开http://www.gurufocus.com/
页面示例 - http://www.gurufocus.com/stock/AES
为什么会这样?也许源类型有点不同或类似的东西?有没有办法阻止访问源代码?
编辑:没有必要调试代码,就在这里,你可以看到这段代码有效。
整个堆叠: 线程“main”中的异常java.lang.IllegalArgumentException:无法打开http://www.gurufocus.com/ 在Algorithms.Tools.In。(In.java:186) 在Investing.TestData.main(TestData.java:16)
答案 0 :(得分:1)
你的问题是它让你回归403;)
您可以尝试向连接添加请求属性。但是我不知道你在哪里打开它,也许在In
对象?
这样的事情:
URLConnection connection = new URL("http://www.gurufocus.com/stock/" + symbol).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
connection.connect();
好的,我试过了,并且使用这个请求属性就可以了,所以完整的代码:
public static void main(String[] args) throws ParseException {
URL page = null;
try {
page = new URL("http://www.gurufocus.com/stock/AES");
URLConnection connection = page.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
System.out.println(a.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
为了完成答案,here是关于网络服务器安全性以及如何阻止Bots的好文章。在这种情况下,你调用的是Bot;)