解析html,pyparser或beautifulsoup

时间:2013-01-11 09:38:19

标签: python

Coast(NS / WS)= EUR35.99 / US $ 46.09

Money Object = EUR42.00 / US $ 53.79

<div id="t142_1" class="text" >Data Center</div>
<div id="t143_1" class="text" >Coast (NS / WS)</div>
<div id="t144_1" class="text" >EUR35.99 / US$46.09</div>
<div id="t145_1" class="text" >Money Object</div>
<div id="t146_1" class="text" >EUR42.00 / US$53.79</div>
<div id="t147_1" class="text" >Date</div>
<div id="t148_1" class="text" >7-Nov-2013 / 7-Nov-2013</div>
<div id="t149_1" class="text" >Opinions</div>

如何使用pyparser或beautifulsoup从“Money Object”和“Coast(NS / WS)”的代码值中获取?

我需要变量(例如):

coast = 'EUR35.99 / US$46.09'

money_obj = 'EUR42.00 / US$53.79'

编辑:

a = soup.find_all(text='Money Object')
for i in a:
    print i.find_next('div').text

但返回:

Change

EUR42.00 / US$53.79

我只需要一个价值(EUR42.00 / US $ 53.79)

2 个答案:

答案 0 :(得分:1)

text是您的示例HTML:

from bs4 import BeautifulSoup as bs

soup = bs(text)
print soup.find(text='Money Object').find_next('div').text
# EUR42.00 / US$53.79

其中的内容为 - 找到Money Object作为其文字内容的内容,然后获取下一个div文字...

答案 1 :(得分:0)

使用pyparsing

from pyparsing import *

data = """\
<div id="t142_1" class="text" >Data Center</div>
<div id="t143_1" class="text" >Coast (NS / WS)</div>
<div id="t144_1" class="text" >EUR35.99 / US$46.09</div>
<div id="t145_1" class="text" >Money Object</div>
<div id="t146_1" class="text" >EUR42.00 / US$53.79</div>
<div id="t147_1" class="text" >Date</div>
<div id="t148_1" class="text" >7-Nov-2013 / 7-Nov-2013</div>
<div id="t149_1" class="text" >Opinions</div>
"""

divS,divE = makeHTMLTags("div")

div = divS + SkipTo(divE).setResultsName("body") + divE
divS.setParseAction( withAttribute(id="t144_1") )

for tokens,start,end in div.scanString(data):
    print "cost = " + tokens.body

divS.setParseAction( withAttribute(id="t146_1") )
for tokens,start,end in div.scanString(data):
    print "money_obj = " + tokens.body

输出:

>>> 
cost = EUR35.99 / US$46.09
money_obj = EUR42.00 / US$53.79