0

我正在尝试根据以前的 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"}

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

4

2 回答 2

0

您可以使用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)
于 2018-09-21T15:42:56.100 回答
0

我对此进行了尝试,出于某种原因,即使在删除 \n 之后,我也无法获得 nextSibling(),因此我尝试了一种不同的策略,如下所示:

from bs4 import BeautifulSoup

"""Lets get rid of the \n""" 
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>""".replace("\n","")
soup = BeautifulSoup(html)
span_list = soup.findAll("span")
result = {span_list[0].text:span_list[1].text.replace(" ","")}

结果如下:

{'名称':'文'}

于 2018-09-21T16:02:07.887 回答