python - 在特定标记后从 html 中提取所有文本?

标签 python html beautifulsoup

我想在特定标记第二次出现后提取 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/

相关文章:

python - 使用 Ipython 并行在 PBS 集群上注册超时

python - 'lxml.etree._ElementTree' 对象没有属性 'cssselect'

java - Base36编码字符串?

HTML 表格固定,右侧显示在左侧

wordpress - 如何创建移动的背景元素

html - CSS类不继承

python - 将部分属性传递到 Beautiful Soup findall 函数

python-3.x - 使用 Selenium 和 Python 将表数据提取到 pandas 数据框中

Python BeautifulSoup 查找包含文本的元素

python - 模型内部的 IntegrityError.Django 中的 DoesNotExist 异常