python - re.compile 如何在 BeautifulSoup 中执行 find_all 函数?

标签 python beautifulsoup

在审查从 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/

相关文章:

python - Lasso正则化器sklearn中的max_iter和tol是什么

python - 使用 Python/Flask 在搜索结果中分页

python - 使用 BeautifulSoup 抓取 Pantip 论坛

python - 使用 BeautifulSoup 在多个页面上编写循环

python - 如何从 matplotlib 中删除工具栏按钮

python - Pandas:计算线性模型系数的脚本在 Linux 上运行良好,但在 Windows 10 上运行不佳

python - 使用 Beautiful Soup 和 Python 抓取 Asp.NET 网站

python - 将邮箱消息转换为 PDF : which part?

python - 如何在Python中使用BeautifulSoup解析多个body标签中的文本?

javascript - 将 Flask Session 与新的 EventSource 结合使用