浅谈Xpath标签属性删除,转换为string,删除标签功能

  • Xpath删除指定标签
# 过程:
#		1.匹配到指定标签
#		2.根据表属性删除
scripts = html.xpath('//script')
for s in scripts:
    s.getparent().remove(s)
  • Xpath删除指定标签属性
#过程:
#		1.匹配到指定标签
#		2.根据strip_attributes方法删除

#strip_attributes 该方法是lxml中etree下的方法,主要是针对标签属性做更改,源码如下:
def strip_attributes(tree_or_element, *attribute_names): # real signature unknown; restored from __doc__
    """
    strip_attributes(tree_or_element, *attribute_names)
    
        Delete all attributes with the provided attribute names from an
        Element (or ElementTree) and its descendants.
    
        Attribute names can contain wildcards as in `_Element.iter`.
    
        Example usage::
    
            strip_attributes(root_element,
                             'simpleattr',
                             '{http://some/ns}attrname',
                             '{http://other/ns}*')
    """
    pass
 
 """示例:"""
 # 删除作者标签的href,a标签
 user = html.xpath('//*[@class="authorName"]')
 etree.strip_attributes(user[0], ["href"])
# 将a标签内的所有属性删除
etree.strip_attributes(user[0], "{}*")
 
  • Xpath替换标签属性值
# 替换指定标签属性值
# 查找img标签
imgs = html.xpath('//*[@class="contentMedia contentPadding"]/div/div/img')
for i in imgs:
    #  替换src属性值
    i.attrib['src'] = "要替换的值"
  • Xpath将etree转换后的页面再次转换为String
html_1 = requests.get(url).content.decode()
html = etree.HTML(html_1)
# 再次转换为String,tostring方法
html_str = etree.tostring(html, encoding="utf-8").decode("utf-8")
print(html_str)

后续不定期更新Xpath的非常用方法,谢谢阅读!!!!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值