简体   繁体   中英

Basic Python/Beautiful Soup Parsing

Say I have used

date = r.find('abbr')

to get

<abbr class="dtstart" title="2012-11-16T00:00:00-05:00">November 16, 2012</abbr>

I just want to print November 16, 2012 , but if I try

print date.string

I get

AttributeError: 'NoneType' object has no attribute 'string'

What am I doing wrong?

ANSWER: Here's my final working code for learning purposes:

soup = BeautifulSoup(page)
calendar = soup.find('table',{"class" : "vcalendar ical"})

dates = calendar.findAll('abbr', {"class" : "dtstart"})
events = calendar.findAll('strong')

for i in range(1,len(dates)-1):
    print dates[i].string + ': ' + events[i].string

soup.find('abbr').string should work fine. There must be something wrong with date .

from BeautifulSoup import BeautifulSoup

doc = '<abbr class="dtstart" title="2012-11-16T00:00:00-05:00">November 16, 2012</abbr>'

soup = BeautifulSoup(doc)

for abbr in soup.findAll('abbr'):
    print abbr.string

Result:

November 16, 2012

Update based on code added to question:

You can't use the text parameter like that.

http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-text

text is an argument that lets you search for NavigableString objects instead of Tags

Either you're looking for text nodes, or you're looking for tags. A text node can't have a tag name.

Maybe you want ''.join([el.string for el in r.findAll('strong')]) ?

The error message is saying that date is None . You haven't shown enough code to say why that is so. Indeed, using the code you posted in the most straight-forward way should work:

import BeautifulSoup

content='<abbr class="dtstart" title="2012-11-16T00:00:00-05:00">November 16, 2012</abbr>'
r=BeautifulSoup.BeautifulSoup(content)
date=r.find('abbr')
print(date.string)
# November 16, 2012

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