473,657 Members | 2,478 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SGML parsing tags and leeping track

Hello,

I need help in using sgmlparser to parse a html file and keep track of
the number of times each tag is being used.

In the end of this program I need to print out the number of times each
tag was seen(presumably any type of tag can be used) and the linked
text.

I need help in getting past the first steps. I already have this basic
program to return hyperlinks. I cant seem to understand how to parse
any tag and keep track of it to print it out at a later time....

very frustrated and help is appreciated!!!! !

--------------------------------------------------------------------------
import sgmllib, urllib

class HtmParser(sgmll ib.SGMLParser):
def __init__(self, verbose=0):
"Initialise an object, passing 'verbose' to the superclass."

sgmllib.SGMLPar ser.__init__(se lf, verbose)
self.hyperlinks = []
self.descriptio ns = []
self.inside_a_e lement = 0

def start_a(self, attributes):
"Process a hyperlink and its 'attributes'."

for name, value in attributes:
if name == "href":
self.hyperlinks .append(value)

def get_hyperlinks( self):
"Return the list of hyperlinks."

return self.hyperlinks
parser = HtmParser()

inptAdrs = raw_input('Plea se input the absolute path to the url\n')
print 'you entered: ', inptAdrs

content = urllib.urlopen( inptAdrs)

bufff = content.read()
print 'Statistics for ', inptAdrs

print 'There is', len(bufff), 'characters in the web page'

parser.feed(buf ff)
print parser.get_hype rlinks()
parser.close()
---------------------------------------------------------------------------------

any help is much appreciated

May 2 '06 #1
3 1410
could i make a global variable and keep track of each tag count?

Also how would i make a list or dictionary of tags that is found?
how can i handle any tag that is given?

May 2 '06 #2
Am Dienstag 02 Mai 2006 20:38 schrieb ha*********@gma il.com:
could i make a global variable and keep track of each tag count?

Also how would i make a list or dictionary of tags that is found?
how can i handle any tag that is given?


The following snippet does what you want:
from sgmllib import SGMLParser

class MyParser(SGMLPa rser):

def __init__(self):
SGMLParser.__in it__(self)
self.tagcount = {}
self.links = set()

# Tag count handling
# ------------------

def handle_starttag (self,tag,metho d,args):
self.tagcount[tag] = self.tagcount.g et(tag,0) + 1
method(args)

def unknown_startta g(self,tag,args ):
self.tagcount[tag] = self.tagcount.g et(tag,0) + 1

# Argument handling
# -----------------

def start_a(self,ar gs):
self.links.upda te([value for name, value in args if name == "href"])

parser = MyParser()
parser.feed(fil e("test.html"). read()) # Insert your data source here...
parser.close()

print parser.tagcount
print parser.links


See the documentation for sgmllib for more info on handle_starttag (whose
logic might just as well have been implemented in start_a, but if you want
argument handling for more tags, it's best to keep it at this one central
place) and unknown_startta g.

--- Heiko.
May 2 '06 #3
Am Dienstag 02 Mai 2006 20:38 schrieb ha*********@gma il.com:
could i make a global variable and keep track of each tag count?

Also how would i make a list or dictionary of tags that is found?
how can i handle any tag that is given?


The following snippet does what you want:
from sgmllib import SGMLParser

class MyParser(SGMLPa rser):

def __init__(self):
SGMLParser.__in it__(self)
self.tagcount = {}
self.links = set()

# Tag count handling
# ------------------

def handle_starttag (self,tag,metho d,args):
self.tagcount[tag] = self.tagcount.g et(tag,0) + 1
method(args)

def unknown_startta g(self,tag,args ):
self.tagcount[tag] = self.tagcount.g et(tag,0) + 1

# Argument handling
# -----------------

def start_a(self,ar gs):
self.links.upda te([value for name, value in args if name == "href"])

parser = MyParser()
parser.feed(fil e("test.html"). read()) # Insert your data source here...
parser.close()

print parser.tagcount
print parser.links


See the documentation for sgmllib for more info on handle_starttag (whose
logic might just as well have been implemented in start_a, but if you want
argument handling for more tags, it's best to keep it at this one central
place) and unknown_startta g.

--- Heiko.
May 2 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1579
by: Fuzzyman | last post by:
I am trying to parse an HTML page an only modify URLs within tags - e.g. inside IMG, A, SCRIPT, FRAME tags etc... I have built one that works fine using the HTMLParser.HTMLParser and it works fine.... on good HTML. Having done a google it looks like parsing dodgy HTML and having HTMLParser choke is a common theme. I would have difficulties using regular expressions as I want to modify local reference URLS as well as absolute ones.
2
1857
by: Martin Krallinger | last post by:
Hi all, I wonder whether there is some sample code or module to parse SGML files in python given the DTD. I would appreciate any help, Best regards,
4
2300
by: silviu | last post by:
I have the following XML string that I want to parse using the SAX parser. If I remove the portion of the XML string between the <audit> and </audit> tags the SAX is parsing correctly. Otherwise SAX wouldn't do the parsing. What's wrong with this string (between <audit> and </audit> tags)? I am using SAX/Xerces 2.3.0 on Sun 8. Thanks in advance of any help. Nick Roman <?xml version="1.0" encoding="UTF-8"?> <lyr3:L3Transaction...
2
3845
by: Christophe Vanfleteren | last post by:
Hello, I'm parsing xml that is returned by the Amazon webservices (using their REST interface). Their dev-heavy.xsd has the following entry: <xs:element name="Track"> <xs:complexType> <xs:sequence>
6
2777
by: S. | last post by:
if in my website i am using the sgml { notation, is it accurate to say to my users that the site uses unicode or that it requires unicode? is there a mathematical formula to calculate a unicode value given its utf8 value? Rgds, Sam
1
2423
by: yonido | last post by:
hello, my goal is to get patterns out of email files - say "message forwarding" patterns (message forwarded from: xx to: yy subject: zz) now lets say there are tons of these patterns (by gmail, outlook, etc) - and i want to create some rules of how to get them out of the mail's html body. so at first i tried using regular expressions: for example - "any pattern that starts with a <p> and contains "from:"..." etc.
3
2396
by: jimmy.williamson | last post by:
Hi, I'm currently working on a project where I am required to investigate how to convert SGML to XML, and then back again. >From what I've seen on the web so far, James Clark's SP software can convert SGML to XML, but thus far I cannot find anything that will go the other way. I realize that in converting SGML to XML I will lose a few things in
2
2797
by: Frantic | last post by:
I'm working on a list of japaneese entities that contain the entity, the unicode hexadecimal code and the xml/sgml entity used for that entity. A unicode document is read into the program, then the program sorts out every doublet and the hexadecimal unicode code is extracted, but I dont know a way to find the xml or sgml-entity equivalent to the unicode code. Anyone who could give me a pointer? Best regards
9
4054
by: ankitdesai | last post by:
I would like to parse a couple of tables within an individual player's SHTML page. For example, I would like to get the "Actual Pitching Statistics" and the "Translated Pitching Statistics" portions of Babe Ruth page (http://www.baseballprospectus.com/dt/ruthba01.shtml) and store that info in a CSV file. Also, I would like to do this for numerous players whose IDs I have stored in a text file (e.g.: cobbty01, ruthba01, speaktr01, etc.)....
0
8420
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8324
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8516
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8617
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7353
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.