BeautifulSoup将文本从[br]提取到[table]

时间:2015-03-23 14:25:29

标签: python beautifulsoup

我正在学习一个学校课程日历,当我尝试提取每门课程的排除时,我遇到了一些问题。(我在抓网:http://www.apsc.utoronto.ca/Calendars/2014-2015/Course_Descriptions.html#ACT240H1

排除是[br]到[table]之前的[a]部分,如下所示的代码:

<br>Exclusion:

                MGT438H1(br)
 <a name="ECE460H1"></a>
<br>



<a name="ACT460H1"></a>

<table border="0" width="100%">

我希望结果是这样的:     &#34;排除:MGT438H1,     ECE460H1     &#34;

虽然下面的代码打印了[br]的所有文字,但我从网站开始到结束。

(我想从&#39; br&#39;到最后一个&#39;以及不包括最后一个&#39;&#39;&#39;&#39;&#39; &#34; ACT460H1&#34;)在[table]之前,有没有办法做到这一点?)

以下是我编写的代码,用于获取[br]到[a]之间的文本:

nextATag = ccpre.find_next('table')

def loopUntilA(text, firstElement):

    if isinstance(firstElement, str):
        text += firstElement
    elif type(firstElement) is Tag:
        text += firstElement.text
    if (firstElement.next.next == nextATag):             
        return text
    else:
    #Using double next to skip the string nodes themselves
        return loopUntilA(text, firstElement.next.next)
targetString = loopUntilA('', ccpre)

print(targetString)

0 个答案:

没有答案