首页 > 解决方案 > Beautifulsoup - 根据前一个 div 子标签从下一个 div 子标签中提取文本

问题描述

我正在尝试根据以前的 div-span text.below 提取下一个 div 跨度中的数据,下面是 html 内容,

<div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:37px; top:161px; width:38px; height:13px;"><span style="font-family: b'Times-Bold'; font-size:13px">Name
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:85px; top:161px; width:58px; height:13px;"><span style="font-family: b'Helvetica'; font-size:13px">Ven
    <br></span></div>

我试图找到文本使用,

n_field = soup.find('span', text="Name\")

然后尝试使用下一个兄弟姐妹获取文本,

n_field.next_sibling()

但是,由于字段中的“\n”,我无法找到跨度并提取 next_sibling 文本。

简而言之,我正在尝试以以下格式形成一个字典,

{"Name": "Ven"}

对此的任何帮助或想法表示赞赏。

标签: pythonpython-3.xpython-2.7beautifulsouppython-beautifultable

解决方案


您可以使用re而不是bs4.

import re

html = """
    <div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:37px; top:161px; width:38px; height:13px;">
        <span style="font-family: b'Times-Bold'; font-size:13px">Name
            <br>
        </span>
    </div>
    <div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:85px; top:161px; width:58px; height:13px;">
        <span style="font-family: b'Helvetica'; font-size:13px">Ven
            <br>
        </span>
    """

mo = re.search(r'(Name).*?<span.*?13px">(.*?)\n', html, re.DOTALL)
print(mo.groups())

# for consecutive cases use re.finditer or re.findall
html *= 5
mo = re.finditer(r'(Name).*?<span.*?13px">(.*?)\n', html, re.DOTALL)

for match in mo:
    print(match.groups())

for (key, value) in re.findall(r'(Name).*?<span.*?13px">(.*?)\n', html, re.DOTALL):
    print(key, value)

推荐阅读