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)
答案 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