有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

span下的java Jsoup html解析项

我试图在Java上使用Jsoup解析项。 当我打开我试图阅读的网站的源代码时

    <ul class="myptab typ3">
        <li><span class="active"><a href="#;" id="ONE_TO_ONE">1+1</a></span></li>
        <li><span><a href="#;" id="TWO_TO_ONE">2+1</a></span></li>
    </ul>


    <h5 class="invisible" >1+1 itemlist</h5>
    <div class="tblwrap mt50">
        <ul class="prod_list">
        </ul>
        <div class="paging">
        </div>
    </div>

    <h5 class="invisible">2+1 itemlist</h5>
    <div class="tblwrap mt50">
        <ul class="prod_list">

        </ul>
        <div class="paging">
        </div>
    </div>

在此源代码中列出了1+1节或2+1节的源代码,但当我使用inspect查看1+1节项上的源代码时

    <h5 class="invisible">1+1 itemlist</h5>
    <div class="tblwrap mt50"> ==$0
    <ul class="prod_list">
      <li>
        <div class="prod_box">
          <p class="img"></p>
          <p class="title">mangomilk_pet_300ML</p>
      </li>
      <li>...</li>
      <li>...</li>
      <li>...</li>
    </ul>

它像那样突然出现。 所以我想从源代码中隐藏的span项中选择p.title和p.img


共 (1) 个答案

  1. # 1 楼答案

    看起来内容是由javascript动态构建的。在这种情况下,jsoup是不够的。您可以尝试使用jBrowserDriver,它能够检索完整的DOM(带有呈现的javascript部分)

    示例代码:

    // Represents result item
    public class ProductBox {
        private final String image;
        private final String title;
    
        public ProductBox(String image, String title) {
            this.image = image;
            this.title = title;
        }
    
        public String getImage() { return image; }
        public String getTitle() { return title; }
    }
    
    
    // Method responsible for parsing a page
    public void processPage(String url) {
        JBrowserDriver driver = new JBrowserDriver(Settings
                .builder()
                .timezone(Timezone.AMERICA_NEWYORK)
                .userAgent(UserAgent.CHROME)
                .build());
    
        driver.get(url);
        String pageSource = driver.getPageSource();
        driver.quit();
    
        Document doc = Jsoup.parse(pageSource);
        Elements prodBoxes = doc.select("ul.prod_list div.prod_box");
        List<ProductBox> products = prodBoxes.stream()
                .map(e -> new ProductBox(e.select("p.img").text(), e.select("p.title").text()))
                .collect(Collectors.toList());
    
        products.forEach(e -> System.out.printf("%s - %s\n", e.getImage(), e.getTitle()));
    }