java - HtmlUnit WebClient 方法 getPage 总是返回相同的页面
问题描述
我目前正在研究一种从特定网站抓取数据的解决方案(使用 css 选择器从网站的 html 表中返回价格列表)。为了做到这一点,我决定使用 HtmlUnit 库,因为我看到它支持很多特性。在我完成代码并针对同一页面(使用相同的搜索参数)对其进行测试后,我认为我已经完成了,但是在为多个页面启动多个线程后一切都发生了变化。问题是基本上下面的代码总是为所有线程返回相同的旧页面,我根本不理解这种行为:
page = client.getPage(webPageURL); // always returns the same old page source
我使用的是同一个网站,我只是更改了一些搜索参数。
这些是我的代码的一些部分:
final WebClient client = new WebClient(BrowserVersion.CHROME);
client.getOptions().setCssEnabled(false);
client.getOptions().setJavaScriptEnabled(true);
client.setAjaxController(new com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController());
client.getOptions().setThrowExceptionOnFailingStatusCode(false);
client.getOptions().setThrowExceptionOnScriptError(false);
client.addRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");
client.addRequestHeader("Pragma", "no-cache");
client.addRequestHeader("Expires", "0"); //
client.getCache().clear();
client.getCache().clearOutdated();
client.getCache().setMaxSize(0);
// enable sessions
client.getCookieManager().setCookiesEnabled(true);
检索页面的地方:
HtmlPage page = null;
try{
//client.closeAllWindows();
page = client.getPage(webPageURL);
WebResponse response = page.getWebResponse();
pageAsString= response.getContentAsString();
正如您所注意到的,我尝试大量使用缓存(因为我认为这是正确的问题?)并通过将页面打印为字符串(pageAsString)进行了一些调试。无论我在页面 url 中更改了多少次搜索参数,都没有任何变化。我总是得到相同的旧页面。
我还尝试了一些删除所有作业或清理页面的方法。不用说,它都不起作用:
finally {
client.getCurrentWindow().getJobManager().removeAllJobs();
page.cleanUp();
client.close();
client.getCurrentWindow().getJobManager().shutdown();
//client.closeAllWindows();
//System.gc();
}
你知道我是怎么弄乱代码的,我总是得到相同的缓存页面吗?
提前谢谢你,n23
解决方案
似乎是与 HtmlUnit 无关的代理问题(有关详细信息,请参阅https://github.com/HtmlUnit/htmlunit/issues/327 )
推荐阅读
- vue.js - Vue:如何将道具设置为数组范围?
- r - 拟合 GAM 时 as.data.frame.default 出错
- twitter - `account.access_token` & `account.refresh_token` 是 `undefined` 当使用 Twitter Provider 和`next-auth` 时?
- react-native - 如何使用 Linking.openURL 在本机反应中打开邮件收件箱
- c++builder - 回到旧的 XE5 C++Builder 平台
- python - 使用循环创建 Flask 端点
- google-apps-script - 如何将第二个参数放置到 google.script.run.withSuccessHandler
- javascript - 当菜单可滚动时,将子菜单保持在屏幕底部
- c# - C# MongoDbDriver - 未设置,无法使其未设置数据库中的字段
- react-native - 获取经度和纬度的更新