我想在特定标记第二次出现后提取 HTML 文件的文本。
我已经尝试过 regex 和 bs4,但我不知道哪里出了问题。正则表达式总是只给我命中本身而没有其余的 html 文件,bs4 只是不起作用,因为我不知道如何指定文件的结尾。
简化:
<html>
<veryspecific tag>
abc
</veryspecific tag>
<stuff that comes before>
</stuff that comes before>
<...
<veryspecific tag>
abc
</veryspecific tag>
<other tags that come after>
something
</other tags that come after>
</...>
<other tags that come after2>
something
</other tags that come after2>
</html>
#I tried splitting it, so I can take the last part which should contain the end of the file, starting from the latest occurrence, but it did not work:
htmltxt.split(r'abc.*$')
# I also tried to get the last tag and try to "while" over the 2 to get the text:
last_tag = html_parsed.findall('a')[-1]
while specific_tag != last_tag:
text = ...
specific_tag = specific_tag.next
我找到了所需的标签并可以提取它,但我还需要文件的其余部分。有没有简单的 pythonic 方法来做到这一点?
最佳答案
这是使用 BeautifulSoup
的建议:
mark = soup.find('veryspecific').find_next('veryspecific')
all_other_tags = mark.find_all_next(name=True)
print(''.join(i.text for i in all_other_tags))
它给了我这个输出:
something
something
关于python - 在特定标记后从 html 中提取所有文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58506434/