【问题标题】:Unexpected character (B) at position 0位置 0 的意外字符 (B)
【发布时间】:2016-08-16 02:53:42
【问题描述】:

我想从这个 url 中抓取数据:http://www.airfrance.fr/FR/fr/local/vols/getInstantFlexNewCalendar.do?idMonth=10&itineraryNumber=1。 我想提取 (Date + Price + Price HT+ Taxe) 然后将它们保存到 Excel 文件中。我使用了这段代码:

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.jsoup.Jsoup;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.javascript.host.dom.Document;

import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;


public class MoisAirfrancee {

    public static void main(String[] args)throws FailingHttpStatusCodeException, MalformedURLException, IOException, RowsExceededException, WriteException{

        Map<String, Integer> prices = new TreeMap<String, Integer>(); 
        File f=new File("C:\\Users\\tahab_000\\Desktop\\Test.xls");
        WritableWorkbook myexcel=Workbook.createWorkbook(f);
        WritableSheet mysheet=myexcel.createSheet("mySheet", 0);        

        try {
            org.jsoup.nodes.Document doc = Jsoup.connect("http://www.airfrance.fr/FR/fr/local/vols/getInstantFlexNewCalendar.do?idMonth=10&itineraryNumber=1").get();

            JSONObject obj = (JSONObject) new JSONParser().parse(doc.text());

            obj = (JSONObject) obj.get("days");

            for (Iterator<?> iterator = obj.keySet().iterator(); iterator.hasNext();) {
                String key = (String) iterator.next();
                JSONObject dateObject = (JSONObject) obj.get(key);
                Double price = (Double) dateObject.get("price");
                int roundedPrice = (int) Math.ceil(price); 

                prices.put(key, roundedPrice);          

            }
            int j=1;

            for (String key : prices.keySet()) {

                addLabel(mysheet, 0, 0, "Date" );
                addLabel(mysheet, 1, 0, "Prix" );
                addLabel(mysheet, 1, j, prices.get(key).toString()+"€" );
                addLabel(mysheet, 0, j, key );

                j++;

                System.out.println(key + ": " + prices.get(key) + " €");
            }
        }catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        myexcel.write();

        myexcel.close();

    }
    private static void addLabel(WritableSheet sheet, int column, int row, String s)
              throws WriteException, RowsExceededException {
            Label label;
            label = new Label(column, row, s);
            sheet.addCell(label);
          }
}

运行后我遇到了这个异常:

Unexpected character (B) at position 0.
    at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
    at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
    at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
    at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
    at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
    at MoisAirfrancee.main(MoisAirfrancee.java:47)

【问题讨论】:

  • 您确定 URL 返回 JSON 吗,您似乎正在提供要解析为 JSON 的数据。当我尝试 URL 时,我得到一个正常的网页

标签: java json web-scraping jsoup jxl


【解决方案1】:

首先连接到默认登录页面 (http://www.airfrance.fr/vols/paris+tunis)。

从响应中,我们可以使用 response.cookies() 获取所需的 cookie,并使用 .cookies(response.cookies()) 设置它/它们以连接到查询页面 (http://www.airfrance.fr/FR/fr/local/vols/getInstantFlexNewCalendar.do?idMonth=10&itineraryNumber=1)

注意:这里可能不需要设置用户代理和引荐来源网址,但它也不会造成伤害并且可能会稳定抓取。

Response response = Jsoup.connect("http://www.airfrance.fr/vols/paris+tunis")
                .userAgent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36")
                .method(Method.GET)
                .timeout(2000)
                .execute();

Document doc = Jsoup
                .connect("http://www.airfrance.fr/FR/fr/local/vols/getInstantFlexNewCalendar.do?idMonth=10&itineraryNumber=1")
                .cookies(response.cookies())
                .userAgent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36")
                .referrer("http://www.airfrance.fr/vols/paris+tunis")
                .timeout(2000)
                .get();

String jsonResponse = doc.text();

System.out.println(jsonResponse);

输出:

{"idMonth":10,"month":"Novembre","bestPrice":270.0,"isLowest":false,"isAvailable":true, ...

【讨论】:

  • 我在 Jsoup 中使用该代码时遇到了异常。如果你能帮助我,我怎么能把我的代码发给你?提前致谢
  • 在这个代码块中,还是在您将它添加到代码库中时?您可以发布您的电子邮件地址/网页/github/...然后我可以联系您。
  • taha.benmohamed@esprit.tn 致以最诚挚的问候
  • 您应该很快就会收到一封邮件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 2019-09-15
  • 2018-07-25
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多