【发布时间】:2016-12-03 03:51:07
【问题描述】:
我正在尝试创建一个程序来查找页面上的扩音器图标,以便我可以通过 if 语句运行它。我正在查看的页面是https://www.yelp.com/biz/sabor-unido-newark。使用 Chrome 上的检查器工具,我找到了扩音器图标的 html:
<span aria-hidden="true" style="fill: #ea5c1d; width: 30px; height: 30px;" class="icon icon--30-bullhorn icon--size-30">
<svg class="icon_svg">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#30x30_bullhorn"></use>
</svg>
</span>
我正在使用 JSoup,并且一直在努力寻找能够实现这一目标的正确方法。基本上我想让它说,“如果页面有扩音器图标,那么就这样做。”我尝试了许多元素选择器和hasAttr() 方法,但似乎都没有。这很可能是因为我对 HTML 不是很流利,并且可能是选择器语法错误。无论如何,你怎么看?
这是我正在使用的当前迭代:
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Attribute;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.Scanner;
public class BullHorn
{
public static void main(String[] args) throws IOException, Exception, RuntimeException
{
String linkUrl = "https://www.yelp.com/biz/mega-pizza-newark?osq=pizza";
Document linkClick = Jsoup.connect(linkUrl).timeout(3000).get();
boolean bullhorn;
for(Element element : linkClick.getAllElements())
{
for(Attribute attribute : element.attributes())
{
if (attribute.getValue().equalsIgnoreCase("#30x30_bullhorn"))
{
bullhorn = true;
}
}
}
if (bullhorn = true)
{
System.out.println("True");
}
else
{
System.out.println("False");
}
}
}
问题是,这总是返回 true,即使在实际上没有扩音器图标的链接上也是如此。
【问题讨论】:
-
感谢您提供您的代码:)
-
if(bullhorn = true)中有一个非常大的语法错误,请记住=是赋值运算符,==检查原语之间的相等性。你也可以将 if 语句写成if(bullhorn)。 -
哇 2 多个小时不断尝试做不同的事情,这是一个缺失的 ='s。那很好笑。谢谢。
-
是的,这会发生,重要的是你没有放弃。看看我的回答,它解决了您代码中的另一个问题。
标签: java html css jsoup selector