【问题标题】:Parsing HTML using BS4 in Python在 Python 中使用 BS4 解析 HTML
【发布时间】:2014-07-23 02:44:25
【问题描述】:

我正在尝试使用以下 HTML 解析网站。

我正在使用 Python 和 BeautifulSoup。

如何从中提取文本 Texas Rangers?

因为不在课堂上,我遇到了麻烦? 谢谢,

马特

<div class="team">
            <span class="team-logo mlb tex"></span>Texas Rangers
                            <br />
                <a class="fancy" href="/split_stats/index/Baseball/Pitcher/107">BvP</a>
                &middot;


                                <a class="fancy" href="/split_stats/index/Baseball/Righty/107">vs. R/a>
                &middot;

                <a class="fancy" href="/split_stats/index/Baseball/Away/107">Away</a>
                &middot;

                                <a class="fancy" href="/split_stats/index/Baseball/Night/107">Night</a>

                    </div>

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup


    【解决方案1】:

    可能不是最好的解决方案,但这是可行的。

    >>> soup = BeautifulSoup(htmlCode)
    >>> soup.div.contents[2].strip()
    u'Texas Rangers'
    

    【讨论】:

      【解决方案2】:

      我将使用我在 ipython 中运行的以下代码:

      In [28]: htmldoc = """<div class="team">
         ....: <span class="team-logo mlb tex"></span>Texas Rangers
         ....: <br />
         ....: <a class="fancy" href="/split_stats/index/Baseball/Pitcher/107">BvP</a>
         ....: &middot;
         ....: <a class="fancy" href="/split_stats/index/Baseball/Righty/107">vs. R/a&gt;
         ....: &middot;
         ....: </a><a class="fancy" href="/split_stats/index/Baseball/Away/107">Away</a>
         ....: &middot;
      <   ....: <a class="fancy" href="/split_stats/index/Baseball/Night/107">Night</a>
         ....: </div>
         ....: """
      
      In [30]: soup = BeautifulSoup(htmldoc)
      
      In [31]: import re
      
      In [32]: soup(text=re.compile('Texas Rangers'))
      Out[32]: [u'Texas Rangers\n']
      

      【讨论】:

      • 美汤的全部意义在于解析 HTML 页面。如果文本不同(不是“Texas Rangers”),那么您的代码将无法正常工作。
      猜你喜欢
      • 2018-12-03
      • 1970-01-01
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多