Python 查找 HTML 标签位置
我需要用 lxml.html
找到标签的位置或者完整的文本内容。
[some html code] </body > [some html code]
比如说,我想返回: </body >
或者这个文本的位置。
我该怎么做呢?下面的代码不管用。
page = fromstring(html)
for s in page.findall('.//body'):
print s.tag, s.text, s.attrib
1 个回答
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)
这里的word是要搜索的字符串,file是文件的路径,都是以字符串的形式传入的。我在下面给了一个例子。
find_position("body", "/home/user/page1.html")
输出结果
24 - <body>
28 - </body>