6

Can someone direct me as how to pull the value of a tag using BeautifulSoup? I read the documentation but had a hard time navigating through it. For example, if I had:

<span title="Funstuff" class="thisClass">Fun Text</span> 

How would I just pull "Funstuff" busing BeautifulSoup/Python?

Edit: I am using version 3.2.1

1
  • Is this BeautifulSoup 3 or BeautifulSoup 4? Commented Jul 23, 2012 at 18:40

2 Answers 2

7

You need to have something to identify the element you're looking for, and it's hard to tell what it is in this question.

For example, both of these will print out 'Funstuff' in BeautifulSoup 3. One looks for a span element and gets the title, another looks for spans with the given class. Many other valid ways to get to this point are possible.

import BeautifulSoup soup = BeautifulSoup.BeautifulSoup('<html><body><span title="Funstuff" class="thisClass">Fun Text</span></body></html>') print soup.html.body.span['title'] print soup.find('span', {"class": "thisClass"})['title'] 
Sign up to request clarification or add additional context in comments.

2 Comments

Question: my import statement for BeautifulSoup is: from BeautifulSoup import BeautifulSoup, CData However, the above code only seems to work when I: import BeautifulSoup Any idea why?
That's just Python. If you are doing a relative import (from BeautifulSoup import BeautifulSoup) then change the line from soup = BeautifulSoup.BeautifulSoup(... to soup = BeautifulSoup(... See docs.python.org/tutorial/modules.html for more.
1

A tags children are available via .contents http://www.crummy.com/software/BeautifulSoup/bs4/doc/#contents-and-children In your case you can find the tag be using its CSS class to extract the contents

from bs4 import BeautifulSoup soup=BeautifulSoup('<span title="Funstuff" class="thisClass">Fun Text</span>') soup.select('.thisClass')[0].contents[0] 

http://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors has all the details nevessary

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.