【问题标题】:Scrapy: checking if the tag has another tag inside it and scrape both elementsScrapy:检查标签内是否有另一个标签并刮掉这两个元素
【发布时间】:2021-06-09 19:15:23
【问题描述】:

我正在尝试抓取使用此结构的 html 页面:

<div class="article-body">
    <div id="firstBodyDiv">
        <p class="ng-scope">
            This is a dummy text for explanation purposes
        </p>
        <p> class="ng-scope">
          This is a <a>dummy</a> text for explanation purposes
        </p>
    </div>
</div>

如您所见,有些 P 元素有 a 元素,有些则没有。 到目前为止我所做的如下:

economics["article_content"] = response.css("div.article-body div#firstBodyDiv > p:nth-child(n+1)::text").extract()

但如果p元素内有a元素,它只返回a元素前后的文本

虽然此查询返回 a(s) 元素:

response.css("div.article-body div#firstBodyDiv p:nth-child(n+1) a::text").extract()

我想找到一种方法来检查是否存在a 元素,以便我可以执行另一个查询(在a 元素中抓取文本的人)

这是我到目前为止所做的:

for i in response.css("div.article-body div#firstBodyDiv p:nth-child(n+1)"):
    if response.css("div.article-body div#firstBodyDiv p:nth-child(n+1) a") in i : 
        # ofcourse this isnt working since and i am getting this error 
        # 'in <string>' requires string as left operand, not SelectorList
        # probably i will have a different list1, list1.append() the p 
        # before, a, and the p text after the a element
        # assign that list to economics["article_content"]

虽然我使用的是 css 选择器,但欢迎您使用 xpath 选择器。

【问题讨论】:

    标签: web-scraping scrapy


    【解决方案1】:

    您可以使用 xpath 中的descendant-or-self 功能,它将获取所有内部文本。

    for i in response.css('div.article-body div#firstBodyDiv > p:nth-child(n+1)'):
     print(''.join(i.xpath('descendant-or-self::text()').extract())) 
    

    您还可以使用scrapy shell 来使用原始 HTML 测试您的代码,如下所示:

    $ scrapy shell
    from scrapy.http import HtmlResponse
    response = HtmlResponse(url='test', body='''<div class="article-body"> 
       <div id="firstBodyDiv"> 
           <p class="ng-scope"> 
               This is a dummy text for explanation purposes 
           </p> 
           <p class="ng-scope"> 
             This is a <a>dummy</a> text for explanation purposes 
           </p> 
       </div> 
    </div> 
    ''', encoding='utf-8')
    for i in response.css('div.article-body div#firstBodyDiv > p:nth-child(n+1)'):
         print(''.join(i.xpath('descendant-or-self::text()').extract())) 
    

    【讨论】:

    • 哇,我以前不知道,你刚刚救了我的命,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 2013-04-17
    • 2013-07-08
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    相关资源
    最近更新 更多