使用BeautifulSoup在<b>和<br>标记中间刮取数据

2024-04-29 02:27:49 发布

您现在位置:Python中文网/ 问答频道 /正文

这是HTML格式:

<td>
        <font face="Arial, sans-serif" size="-1">

                    <b>Home Phone: </b>507-383-1070<br>

                    <b>Cell Phone: </b>507-383-1070<br>

                    <b>E-Mail: </b><a href=mailto:macehrhardt@gmail.com>macehrhardt@gmail.com</a><br>

        </font>
</td>

我只想获取Home Phone和{}的数据,例如507-383-1070。你能帮我解决这个问题吗?我将如何使用BeautifulSoup来解决这个问题。我尝试了多种方法,但没有找到任何方法。在


Tags: 方法brcomhomehtml格式phonegmail
2条回答

对于您给出的HTML,可以按如下方式提取:

from bs4 import BeautifulSoup

html = """<td>
        <font face="Arial, sans-serif" size="-1">
                    <b>Home Phone: </b>507-383-1070<br>
                    <b>Cell Phone: </b>507-383-1070<br>
                    <b>E-Mail: </b><a href=mailto:macehrhardt@gmail.com>macehrhardt@gmail.com</a><br>
        </font>
</td>"""

soup = BeautifulSoup(html, "html.parser")
entries = [b.next.next for b in soup.find_all('b')][:2]

print entries 

给你:

^{pr2}$

可以将soup.find_all与正则表达式一起使用。在

>>> soup.find_all(text=re.compile('\d+(-\d+){2}'))
['507-383-1070', '507-383-1070']

您可能需要根据要提取的电话号码的格式来调整正则表达式。在

相关问题 更多 >