我正在尝试创建一个程序来查找页面上的扩音器图标,以便我可以通过 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)
中有语法错误,请记住 =
是赋值运算符,而 ==
' s 检查基元之间的相等性。您也可以将 if 语句写成 if(bullhorn)
。
附带说明,但仍然很重要:
如果您找到扩音器,您应该中断
for 循环,没有必要继续遍历每个元素。
例如:
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;
// no need to continue looping, we've found bullhorn
break;
}
}
// no need to continue looping, we've found bullhorn
if(bullhorn == true) {
break;
}
}
if (bullhorn == true) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
关于java - 如何让我的程序检查页面上是否存在图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40939618/