http://www.biletix.com/search/TURKIYE/en#!subcat_interval:12/12/15TO19/12/15
我想从这个网站获取数据。当我使用 jsoup
时,由于 javascript,它无法执行。尽管我所有的努力,仍然无法管理。
如您所见,我只想获取名称和网址。然后我可以转到该 url 并获取开始-结束时间和位置。
我不想使用 headless 浏览器。您知道其他选择吗?
最佳答案
有时基于 javascript 和 json 的网页比纯 html 网页更容易抓取。
如果您仔细检查网络流量(例如,使用浏览器开发人员工具),您会发现该页面正在发出 GET 请求,该请求返回一个包含您需要的所有数据的 json 字符串。您将能够使用任何 json 库解析该 json。
网址是:
您可以按照与生成您在问题中输入的 URL 类似的方式生成此 URL。
您将获得的 json fragment 是:
....
"id":"SZ683",
"venuecount":"1",
"category":"ART",
"start":"2015-12-12T18:30:00Z",
"subcategory":"tiyatro$ART",
"name":"The Last Couple to Meet Online",
"venuecode":"BT",
.....
您可以看到名称和 URL 是使用 id
字段 (SZ683) 轻松生成的,例如:http://www.biletix.com/etkinlik/SZ683/TURKIYE/en
-------- 编辑 --------
获取json数据比我最初想象的要难。服务器需要 cookie 才能返回正确的数据,因此我们需要:
- 要执行第一个 GET,请获取 cookie 并执行第二个 GET 以获取 json 数据。使用 Jsoup 很容易。
- 然后我们将使用 org.json 解析响应。
这是一个工作示例:
//Only as example please DON'T use in production code without error control and more robust parsing
//note the smaller change in server will break this code!!
public static void main(String[] args) throws IOException {
//We do a initial GET to retrieve the cookie
Document doc = Jsoup.connect("http://www.biletix.com/").get();
Element body = doc.head();
//needs error control
String script = body.select("script").get(0).html();
//Not the more robust way of doing it ...
Pattern p = Pattern.compile("document\\.cookie\\s*=\\s*'(\\w+)=(.*?);");
Matcher m = p.matcher(script);
m.find();
String cookieName = m.group(1);
String cookieValue = m.group(2);
//I'm supposing url is already built
//removing url last part (json.wrf=jsonp1450136314484) result will be parsed more easily
String url = "http://www.biletix.com/solr/tr/select/?start=0&rows=100&q=subcategory:tiyatro$ART&qt=standard&fq=region:%22ISTANBUL%22&fq=end%3A%5B2015-12-15T00%3A00%3A00Z%20TO%202017-12-15T00%3A00%3A00Z%2B1DAY%5D&sort=start%20asc&&wt=json";
Document document = Jsoup.connect(url)
.cookie(cookieName, cookieValue) //introducing the cookie we will get the corect results
.get();
String bodyText = document.body().text();
//We parse the json and extract the data
JSONObject jsonObject = new JSONObject(bodyText);
JSONArray jsonArray = jsonObject.getJSONObject("response").getJSONArray("docs");
for (Object object : jsonArray) {
JSONObject item = (JSONObject) object;
System.out.println("name = " + item.getString("name"));
System.out.println("link = " + "http://www.biletix.com/etkinlik/" + item.getString("id") + "/TURKIYE/en");
//similarly you can fetch more info ...
System.out.println();
}
}
我跳过了 URL 生成,因为我想你知道如何生成它。
我希望所有的解释都很清楚,英语不是我的第一语言,所以我很难解释自己。
关于javascript - 我如何从 Android 中具有高 javascript 的网站检索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34241602/