【发布时间】:2018-09-24 18:52:56
【问题描述】:
我正在尝试抓取这样的表格:
<table><tr>
<td width="100"><p><span style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt;">My title example:</span></p></td>
<td width="440"><p><span style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt;">My text example.</span></p></td>
</tr>
<tr>
<td width="100">My second title:</p></td>
<td width="440"><p>My <span style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; text-decoration: underline;">second</span> text example.</p></td>
</tr></table>
在一个简单的字典列表中显示输出,如下所示:
[
{"title": "My title example", "text": "My text example"},
{"title": "My other example", "text": "My <u>second</u> text example"},
{"title": "My title example", "text": "My new example"},
]
但我需要清理代码并将下划线部分交换为标记。所以这是我到目前为止的代码:
from bs4 import BeautifulSoup
import re
# Find the rows in the table
for table_row in html.select("table tr"):
cells = table_row.findAll('td')
if len(cells) > 0:
row_title = cells[0].text.strip()
paragraphs = []
# Find all spans in a row
for run in cells[1].findAll('span'):
print(run)
if "text-decoration: underline" in str(run):
paragraphs.append("{0}{1}{2}".format("<u>", run.text, "</u>"))
else:
paragraphs.append(run.text)
# Build up a sanitized string with all the runs.
row_text = "".join(paragraphs)
row = {"title": row_title, "text": row_text}
data.append(row)
print(data)
问题:您可能已经注意到,它抓取完美跨度的行(第一个示例),但它在第二个示例中失败,并且仅 刮 下划线部分(因为文本不在 span 标签内)。所以我在想,与其尝试查找跨度,不如删除所有跨度并用正则表达式替换我需要的跨度,如下所示:
# Find all runs in a row
for paragraph in cells[1].findAll('p'):
re.sub('<.*?>', '', str(paragraph))
这将创建没有标签的文本,但也没有下划线格式,这就是我卡住的地方。
我不知道如何在正则表达式上添加这样的条件。欢迎任何帮助。
预期输出:从段落中删除所有标签,但将找到text-decoration: underline 的跨度替换为<u></u> 标签。
【问题讨论】:
标签: python regex python-3.x beautifulsoup