简体   繁体   中英

Parsing html, pyparser or beautifulsoup

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>

How to get from this code value of "Money Object" and "Coast (NS / WS)" using pyparser or beautifulsoup?

I need variables (for example):

coast = 'EUR35.99 / US$46.09'

money_obj = 'EUR42.00 / US$53.79'

EDIT:

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

but return:

Change

EUR42.00 / US$53.79

I need only one value (EUR42.00 / US$53.79)

Where text is your example 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

Which reads as - find something with Money Object as its text content, then take the next div s text...

Using 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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM