python - 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"}
对此的任何帮助或想法表示赞赏。
解决方案
您可以使用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)
推荐阅读
- python - conda 降级 numpy 版本
- javascript - 在Angular中的ngClass中绑定自定义类
- oracle - 同义词上的授予命令引发 ORA-01775 错误
- angular - 非常相似的组件和模板。如何重用它们?
- android - Android Studio CMake 不会将预建库链接到主 .so 文件
- outlook - 为什么 Office.context.mailbox.item.dateTimeCreated 返回 PR_LAST_MODIFICATION_TIME 而不是 PR_MESSAGE_DELIVERY_TIME?
- bash - 将文本添加到带有变量的特定行号
- verilog - 如何根据交叉覆盖点的总和限制交叉点箱?binsof是什么意思?
- python - Systemd 服务有时会在启动时崩溃
- qt - 在 Qt QML 中设置 VideoOutput 项