如何可靠地提取meta标签中的属性和内容?
我有一些HTML代码,比如下面这些行。我需要提取出og:image
和content
这两个属性的值。问题是,如果我直接用简单的字符串分割方法,比如string.split(),那么结果在下面的行中就会不一样,因为第二行的content
值中有很多空格。
我该如何可靠地处理这些字符串行,并得到像这样的列表:['og:image', 'http....whatever.jpg']
,第二行也是一样的?
<meta property="og:image" content="http://google.com/example.jpg"/>
<meta property="og:title" content="Fant over 300 falske personer i skattelistene"/>
编辑:现在我这样解析:
tree = etree.HTML( xml )
m = tree.xpath("//meta[@property]")
for i in m:
og = etree.tostring( i )
print og # <meta property="og:image" content="http://google.com/example.jpg"/>
也许可以用XPath直接把content/property提取到一个列表中?
1 个回答
1
与其把你的元素再转换回字符串,不如直接通过每个元素的 attrib
属性来获取它们的属性值:
for i in m:
print (i.attrib['property'], i.attrib['content'])