在审查从 html 表构建 csv 的解决方案时,我偶然发现了这段代码
ol = map(cell_text, row.find_all (re.compile('t[dh]')))
粗体文本到底发生了什么? find_all 调用 html 元素和标签。粗体文本是如何实现这一点的?
上下文如下
#!/usr/bin/python
from bs4 import BeautifulSoup
import sys
import re
import csv
def cell_text(cell):
return " ".join(cell.stripped_strings)
soup = BeautifulSoup(sys.stdin.read())
output = csv.writer(sys.stdout)
for table in soup.find_all('table'):
for row in table.find_all('tr'):
col = map(cell_text, row.find_all(re.compile('t[dh]')))
output.writerow(col)
output.writerow([])
最佳答案
它会查找所有 t 后跟 d 或 h。 re.compile
只是返回“已编译”的正则表达式对象,供 find_all
使用。
这是 re.compile 的文档; BeautifulSoup 的 find_all
可以采用正则表达式;这是 sample from the documentation :
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
如您所见,使用方式非常相似
关于python - re.compile 如何在 BeautifulSoup 中执行 find_all 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40944179/