在Python中使用BS4解析HTML

时间:2014-07-23 02:44:26

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

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

我正在使用Python和BeautifulSoup。

如何从中提取文本德州游骑兵?

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

马特

<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>

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

我会使用以下在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']