Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a tag called "name" in BeautifulSoup

I want to access a tag called as "name" such as:

<contact><name>Yesügey</name><lastName>Yeşil</lastName><phone>+90 333 9695395</phone></contact>

Since "name" is a property of a BeautifulSoup tag object, I cannot access the child tag name:

>>> c1
<contact><name>Yesügey</name><lastname>Yeşil</lastname><phone>+90 333 9695395</p
hone></contact>
>>> c1.name
'contact'
>>> c1.lastname
<lastname>Yeşil</lastname>
like image 421
Mert Nuhoglu Avatar asked Jan 21 '13 08:01

Mert Nuhoglu


People also ask

How do you find something in the BeautifulSoup?

Beautiful Soup provides "find()" and "find_all()" functions to get the specific data from the HTML file by putting the specific tag in the function. find() function - return the first element of given tag. find_all() function - return the all the element of given tag.

How do you get a href value in BeautifulSoup?

To get href with Python BeautifulSoup, we can use the find_all method. to create soup object with BeautifulSoup class called with the html string. Then we find the a elements with the href attribute returned by calling find_all with 'a' and href set to True .

What is a tag in BeautifulSoup?

Going down. One of the important pieces of element in any piece of HTML document are tags, which may contain other tags/strings (tag's children). Beautiful Soup provides different ways to navigate and iterate over's tag's children.


2 Answers

You can try like this,

>>> soup=BeautifulSoup.BeautifulSoup(content).findAll('name')
>>> for field in soup:
...     print field
... 
<name>Yesügey</name>

Or

print soup.find('name').string
like image 67
Adem Öztaş Avatar answered Sep 28 '22 07:09

Adem Öztaş


Here's what I got:

from bs4 import BeautifulSoup as BS
soup = '<contact><name>Yesügey</name><lastName>Yeşil</lastName><phone>+90 333 9695395</phone></contact>'
soup = BS(soup)
print soup.find('name').string
# Prints YesĂźgey

So instead of calling the name tag, I simply find it and get what's inside it :).

like image 28
TerryA Avatar answered Sep 28 '22 07:09

TerryA