【问题标题】:Scrape data middle of <b> and <br> tag using BeautifulSoup使用 BeautifulSoup 刮取 <b> 和 <br> 标签的中间数据
【发布时间】:2017-10-08 19:36:11
【问题描述】:

这是 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 PhoneCell Phone 的数据,例如。 507-383-1070。你能帮我看看我将如何使用 BeautifulSoup 来解决这个问题。我尝试了多种方法,但没有找到任何方法。

【问题讨论】:

  • 请向我们展示您已经尝试过的内容。
  • @sn3jd3r 在代码中我刚刚得到了&lt;b&gt; 标签之间的数据,而不是数字
  • 提示:使用正则表达式

标签: python beautifulsoup


【解决方案1】:

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

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

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

【讨论】:

  • 如果我只想刮Home Phone那我该怎么办?
  • @RageebArtho 你应该提出一个新问题,这是你应该做的。先关闭这个accept an answer,然后根据你的确切问题问一个新的。
  • 我只能在 90 分钟内发帖。那么你能在这里给出你的答案吗?
  • @RageebArtho 我可以想到一个涉及find_all 的解决方案 - 查找所有b 标签,将文本与Home Phone 进行比较,如果匹配,请使用tag.nextSibling()(或类似的排序 - 检查文档)并访问其文本属性。
  • 这是给我TypeError: 'NavigableString' object is not callable
【解决方案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 

给你:

[u'507-383-1070', u'507-383-1070']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 2019-06-03
    相关资源
    最近更新 更多