使用 Jsoup 从网站抓取文本时遇到问题



我试图从亚马逊链接中获取价格。

这是我关注的 html:

<div class="buying" id="priceBlock">
    <table class="product">
        <tbody>
            <tr id="actualPriceRow">
                <td class="priceBlockLabelPrice" id="actualPriceLabel">Price:</td>
                <td id="actualPriceContent">
                    <span id="actualPriceValue">
                        <b class="priceLarge">
                                $1.99
                        </b>
                    </span>
                </td>
            </tr>
        </tbody>
    </table>
</div>                

我试图抓住那篇1.99美元的文字。

这是我试图抓住它的代码。

protected Void doInBackground(Void... params) {
            try {
                // Connect to the web site
                Document document = Jsoup.connect(url).get();
                // Get the html document title
                Elements trs = document.select("table.product");

                for (Element tr : trs)
                {
                    Elements tds = tr.select("b.priceLarge");
                    Element price1 = tds.first();
                    String str1 = price1.text();
                    System.out.println(str1);
                    String str2 = str1.replaceAll( "[$,]", "" );
                    double aInt = Double.parseDouble(str2);
                    System.out.println("Price: " + aInt);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

为什么这段代码不起作用?

您必须

使用user agent,这样网站就不会拒绝您作为机器人。您还应该添加一些超时限制,以覆盖默认限制,这对您来说可能太短了。三秒钟是一个不错的选择,但可以随意更改它。 只要服务器需要给出一些响应,timeout(0)就会等待。如果您不想要限制,请使用它。您正在执行的解析也有一些奇怪的DOM,这会导致NullPointerException。试试这个

String url = "http://www.amazon.com/dp/B00H2T37SO/?tag=stackoverfl08-20";
Document doc = Jsoup
                .connect(url)
                .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36")
                .timeout(3000)
                .get();
Elements prices = doc.select("table.product b.priceLarge");
for (Element pr : prices)
{
    String priceWithCurrency = pr.text();
    System.out.println(priceWithCurrency);
    String priceAsText = priceWithCurrency.replaceAll( "[$,]", "" );
    double priceAsNumber = Double.parseDouble(priceAsText);
    System.out.println("Price: " + priceAsNumber);
}   

最新更新