2011-11-26 72 views
1

我需要使用lxml.html找到标签的位置或全文。 例如:Python找到HTML标签位置

[some html code] </body > [some html code] 

我需要返回:</body > OR这段文字的位置。

我该怎么做?下面的代码不起作用。

page = fromstring(html) 
for s in page.findall('.//body'): 
    print s.tag, s.text, s.attrib 
+0

目前还不清楚是什么 “位置或标记的全文” 的意思。 ''是'body'元素的结束标记。什么是位置?你的意思是行号? – mzjn

回答

0

我已经定义了一个Python函数下面将给出的文件中对于给定的搜索字符串并在串中发现打印行号和行内容。

def find_position(word, file): 
    line_number = 0 
    for line in open(file): 
     line_number += 1 
     if word in line: 
      print "%d - %s" % (line_number, line) 

这里单词需要单词作为字符串进行搜索,文件将文件的路径作为字符串进行搜索。我已经给出了下面的例子。

find_position("body", "/home/user/page1.html") 

输出

24 - <body> 
28 - </body>