使用lxml在Python中获取<img>的title属性

0 投票
2 回答
3060 浏览
提问于 2025-04-16 21:07

我想用Python从这个网站提取一些单行文本。网站上的信息在HTML中看起来是这样的:

<div class="olh_message"> 
    <p>foobarbaz <img src="/static/emoticons/support-our-fruits.gif" title=":necta:" /></p> 
</div> 

到目前为止,我的代码是这样的:

import lxml.html
url = "http://www.scenemusic.net/demovibes/oneliner/"
xpath = "//div[@class='olh_message']/p"
tree = lxml.html.parse(url)
texts = tree.xpath(xpath)
texts = [text.text_content() for text in texts]
print(texts)

但是,现在我只得到了foobarbaz,我其实想要把里面图片的标题参数也提取出来,所以在这个例子中我想要的是foobarbaz :necta:。看起来我需要使用lxml的DOM解析器来实现这个功能,但我不知道该怎么做。有没有人能给我一点提示?

提前谢谢大家!

2 个回答

0

使用方法:

//div[@class='olh_message']/p/node()

这段代码会选择所有在任何 div 元素下的 p 元素的子节点,包括元素、文本节点、处理指令和注释节点,而这些 div 元素的 class 属性是 'olh_message'

使用 XSLT 验证 XPath:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/">
     <xsl:copy-of select="//div[@class='olh_message']/p/node()"/>
 </xsl:template>
</xsl:stylesheet>

当这个转换应用于以下 XML 文档时:

<div class="olh_message">
    <p>foobarbaz 
        <img src="/static/emoticons/support-our-fruits.gif" title=":necta:" />
    </p>
</div>

会产生我们想要的正确结果(这表明 XPath 表达式确实选择了我们想要的节点):

foobarbaz 
        <img src="/static/emoticons/support-our-fruits.gif" title=":necta:"/>
1

试试这个

  import lxml.html
  url = "http://www.scenemusic.net/demovibes/oneliner/"
  parser = lxml.etree.HTMLParser()
  tree = lxml.etree.parse(url, parser)
  texts = tree.xpath("//div[@class='olh_message']/p/img/@title")

撰写回答