【问题标题】:Exclude div from Scrapy从 Scrapy 中排除 div
【发布时间】:2016-03-19 05:41:31
【问题描述】:

我有这个 html:

<div id="content">
    <h1>Title 1</h1><br><br>

    <h2>Sub-Title 1</h2>
    <br><br>
    Description 1.<br><br>Description 2.
    <br><br>

    <h2>Sub-Title 2</h2>
    <br><br>
    Description 1<br>Description 2<br>
    <br><br>

    <div class="infobox">
        <font style="color:#000000"><b>Information Title</b></font>
        <br><br>Long Information Text
    </div>
</div>

我想在Scrapy中获取&lt;div id="content"&gt;中的所有html但不包括&lt;div class="infobox"&gt;的块,所以预期的结果是这样的:

<div id="content">
    <h1>Title 1</h1><br><br>

    <h2>Sub-Title 1</h2>
    <br><br>
    Description 1.<br><br>Description 2.
    <br><br>

    <h2>Sub-Title 2</h2>
    <br><br>
    Description 1<br>Description 2<br>
    <br><br>
</div>

如何修改我当前的选择器:

item['article_html'] = hxs.select("//div[@id='content']").extract()[0]

【问题讨论】:

    标签: python html xpath web-scraping scrapy


    【解决方案1】:

    没有直接的方法可以直接使用选择器 (xpath) 执行此操作。

    你可以这样做:

    content = hxs.select("//div[@id='content']").extract()[0]
    infobox = hxs.select("//div[@id='content']//div[@class='infobox']").extract()[0]
    
    item['article_html'] = content.replace(infobox, "")
    

    【讨论】:

      【解决方案2】:

      您可以操作元素树来删除有问题的 div:

      >>> from scrapy.http import HtmlResponse
      >>> body = '''\
      ... <div id="content">
      ...     <h1>Title 1</h1><br><br>
      ... 
      ...     <h2>Sub-Title 1</h2>
      ...     <br><br>
      ...     Description 1.<br><br>Description 2.
      ...     <br><br>
      ... 
      ...     <h2>Sub-Title 2</h2>
      ...     <br><br>
      ...     Description 1<br>Description 2<br>
      ...     <br><br>
      ... 
      ...     <div class="infobox">
      ...         <font style="color:#000000"><b>Information Title</b></font>
      ...         <br><br>Long Information Text
      ...     </div>
      ... </div>
      ... '''
      >>> resp = HtmlResponse(url='http://example.com', body=body, encoding='utf8')
      >>> xhs = resp.selector
      >>> infobox = xhs.css('.infobox')[0].root
      >>> infobox.getparent().remove(infobox)
      >>> print(xhs.select("//div[@id='content']").extract()[0])
      <div id="content">
          <h1>Title 1</h1><br><br>
      
          <h2>Sub-Title 1</h2>
          <br><br>
          Description 1.<br><br>Description 2.
          <br><br>
      
          <h2>Sub-Title 2</h2>
          <br><br>
          Description 1<br>Description 2<br>
          <br><br>
      
          </div>
      

      【讨论】:

        【解决方案3】:

        您还可以使用 CSS 选择器 :not(...) 排除事物。

        虽然完全未经测试,尝试这样的事情:

        response.css("div[id='content']:not([class*='infobox'])")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-16
          • 2019-04-07
          • 1970-01-01
          • 2011-05-18
          相关资源
          最近更新 更多