2024-04-24 08:32:04 发布
网友
我使用Python来操作HTML字符串。我想 从给定文本中查找父标记(开始和结束);html字符串中文本的结束偏移量(已知)
例如,考虑以下html字符串
<html><body><span id="1234">The Dormouse's story</span><body></head>
输入是偏移量(33,43),即字符串'Dormouse's',父标记是<span id="1234">
<span id="1234">
就在我的头顶,因为你有偏移量(我想你可能需要调整,因为我必须使用(28,48))
split()
>
子字符串列表中倒数第二个子字符串是父标记(因为如果分隔符位于要拆分的字符串的末尾,拆分列表将返回空字符串):
html_string = '<html><body><span id="1234">The Dormouse\'s story</span><body></head>' offset_string = html_string[28:48] tags_together = html_string.split(offset_string)[0] list_of_tags = tags_together.split('>') parent_tag = list_of_tags[len(list_of_tags)-2]
请注意,您将缺少一个“>;”所以如果有必要的话,你得加回去
parent_tag = parent_tag + ">"
另外,我之所以把html_string放在单引号中,是因为已经有双引号了
html_string
这是恶心的,有点野蛮,但它应该得到的工作完成I am sure there exists a python library out there that can do this kind of task for you. You just need to look hard enough!
我建议打开一个pythonshell,在创建每个变量之后打印出来,这样就可以看到split()的作用Here are some docs for that!
现在我想起来了,使用带有已知偏移量的regex也可以得到标签
就在我的头顶,因为你有偏移量(我想你可能需要调整,因为我必须使用(28,48))
split()
将偏移量字符串作为分隔符拆分整个html字符串李>>
将其拆分李>子字符串列表中倒数第二个子字符串是父标记(因为如果分隔符位于要拆分的字符串的末尾,拆分列表将返回空字符串):
请注意,您将缺少一个“>;”所以如果有必要的话,你得加回去
另外,我之所以把
html_string
放在单引号中,是因为已经有双引号了这是恶心的,有点野蛮,但它应该得到的工作完成I am sure there exists a python library out there that can do this kind of task for you. You just need to look hard enough!
我建议打开一个pythonshell,在创建每个变量之后打印出来,这样就可以看到
split()
的作用Here are some docs for that!现在我想起来了,使用带有已知偏移量的regex也可以得到标签
相关问题 更多 >
编程相关推荐