在xpath中使用正则表达式

xpath中使用正则表达式

其实我自己也从来没用到过,在此记录一下,万一以后会用到呢。
比如有个网站正文部分是: //*[@id='postmessage_32199']
另一个同级别页面的正文是: //*[@id='postmessage_32153']
要抓取这种正文其实可以用xpath: //*[starts-with(@id, 'postmessage_')]
或者 //*[contains(@id, 'postmessage_')]
也可以选择在xpath中使用正则表达式:doc.xpath(r'//*[re:match(@id, "postmessage_d+")]', namespace={"re": "http://exslt.org/regular-expressions"})

xpath中如何看选住原文的内容

选取页面元素el,通过to_string 方法可以拿到页面标签的原文不过是bytes类型,可以用bytes.decoding
result = etree.tostring(el)
print(result.decode('utf-8'))
原文地址:https://www.cnblogs.com/presleyren/p/12786359.html