gpt4 book ai didi

java - 使用 Jsoup 从网站获取文本时遇到问题

转载 作者:行者123 更新时间:2023-11-30 02:28:57 26 4
gpt4 key购买 nike

我正在尝试从亚马逊获取价格 link.

这是我关注的 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;
}

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

最佳答案

您必须使用用户代理,这样站点才不会将您作为bot 拒绝。 .您还应该添加一些超时限制以覆盖默认值,这对您来说可能太短了。三秒是一个不错的选择,但您可以随意更改它。 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);
}

关于java - 使用 Jsoup 从网站获取文本时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27538936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com