• xpath排除特定子节点


    一直用xpath提取网页数据,有些文章嵌入一些图片 a标签等,一般的通用做法是用【正则】去除,可是也很难满足要求,

    尤其是要提取的内容跟图片和a标签在相同的标签里

     如上图,都在p标签里,不管是内容还是图片,这时用正则也不是很灵活,现在办法是通过提取到文章主体部分,然后依次遍历每个段落,

                div_list = []
                div = response.xpath(
                    '//div[@id="articlebody"]/*[not(name()="style") and not(@class="instrumentName") and not(@id="botlist")]').getall()
                if not div:
                    # articleContent
                    div = response.xpath(
                        '//div[@class="articleContent"]/*[not(name()="h4") and not(name()="div")]').getall()
                if div and len(div) > 0:
                    for dv in div:
                        if "</a>" not in dv or "<img" not in dv:
                            div_list.append(dv)
                div_html = '''<div class="cont-cont">{0} </div>'''.format(
                    "".join(div_list))
    

     这里只提取p标签和h3标签,遍历后如果内容中含有图片和a标签则删除,这样就可以处理排除掉特定子元素

  • 相关阅读:
    Transformer详解
    PAT 1012
    PAT 1011
    PAT 1010
    Jordan Lecture Note-3: 梯度投影法
    PAT 1009
    PAT 1008
    Jordan Lecture Note-2: Maximal Margin Classifier
    PAT 1007
    PAT 1006
  • 原文地址:https://www.cnblogs.com/fly-kaka/p/15384263.html
Copyright © 2020-2023  润新知