Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python debuggers
#8
(Jul-10-2023, 10:57 PM)jehoshua Wrote: so I need to inspect "tag". Is it an object, a class, a variable ??
Yes,this is more that you have not used Beautiful Soup much and make mistakes.
Also even if tag(bs4.element.Tag) worked,so will this not work as children is just and iterator(used in loop),and have no attributes name.

Quick example,with a xml that has more content that you previos thread.
from bs4 import BeautifulSoup

with open('breakfast.xml') as f:
    file = f.read()

soup = BeautifulSoup(file, 'xml')
food = soup.find('food')
See that food is a bs4.element.Tag.
>>> type(food)
<class 'bs4.element.Tag'
>>> food.find('price')
<price>$5.95</price>
>>> food.find('price').text
'$5.95'

# This work now but make no sense to use as this
>>> food.children
<list_iterator object at 0x0000017E966A6260>
Iterate over and get both prices.
from bs4 import BeautifulSoup

with open('breakfast.xml') as f:
    file = f.read()

soup = BeautifulSoup(file, 'xml')
for tag in soup.find_all('food'):
    print(tag.find('price'))
    print(tag.find('price').text)
Output:
<price>$5.95</price> $5.95 <price>$7.95</price> $7.95
File used breakfast.xml:
Output:
<?xml version="1.0" encoding="UTF-8"?> <breakfast_menu> <food> <name>Belgian Waffles</name> <price>$5.95</price> <description> Two of our famous Belgian Waffles with plenty of real maple syrup </description> <calories>650</calories> </food> <food> <name>Strawberry Belgian Waffles</name> <price>$7.95</price> <description> Light Belgian waffles covered with strawberries and whipped cream </description> <calories>900</calories> </food> </breakfast_menu>
jehoshua likes this post
Reply


Messages In This Thread
Python debuggers - by jehoshua - Jul-04-2023, 10:51 PM
RE: Python debuggers - by snippsat - Jul-05-2023, 04:30 PM
RE: Python debuggers - by jehoshua - Jul-07-2023, 12:40 AM
RE: Python debuggers - by deanhystad - Jul-07-2023, 03:37 AM
RE: Python debuggers - by jehoshua - Jul-07-2023, 04:38 AM
RE: Python debuggers - by deanhystad - Jul-07-2023, 11:48 AM
RE: Python debuggers - by jehoshua - Jul-10-2023, 10:57 PM
RE: Python debuggers - by snippsat - Jul-11-2023, 02:16 PM
RE: Python debuggers - by jehoshua - Jul-20-2023, 07:48 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020