【问题标题】:Jsoup html parsing items under spanspan下jsoup html解析项目
【发布时间】:2016-11-10 02:30:08
【问题描述】:

我正在尝试在 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 部分,但是当我使用检查查看 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>

它会像那样弹出。 所以我想从源代码中隐藏的跨度项中选择p.title和p.img。

【问题讨论】:

    标签: java html parsing jsoup


    【解决方案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()));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多