473,698 Members | 2,546 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Finding Line numbers of HTML file

I am doing some HTML scrapping for a side project.

I need a method using sgmllib or HTMLParser to parse an HTML file and
get line nos of all the tags

I tried a few things, but I am just not able to work with either if
the parsers.

Can someone help

Dec 12 '07 #1
5 1880
Ramdas wrote:
I am doing some HTML scrapping for a side project.

I need a method using sgmllib or HTMLParser to parse an HTML file and
get line nos of all the tags

I tried a few things, but I am just not able to work with either if
the parsers.

Can someone help
HTML doesn't really have "lines" it is just a stream of text that can be
formatted with line end characters to make it somewhat easier for humans to
read. Parsers probably won't give you any line numbers. What is the use case
for this (e.g. why do you think you need the line numbers)? Extraction is done
using tags not line numbers. All that said, you should look at Beautiful Soup
module before continuing.

-Larry
Dec 12 '07 #2
Hi Paul,

I am cross posting the same to grab your attention at pyparsing forums
too. 1000 apologies on the same count!

I am a complete newbie to parsing and totally new to pyparsing.

I have adapted your code to store the line numbers as below.
Surprisingly, the line numbers printed, when I scrap some of the URLs,
is not accurate and is kind of way off.
page = urlli2b.urlopen ("www.....com). read()

def tallyTagLineNum ber(strg, locn, tagTokens):
line = lineno(locn,str g)
tagLocs[tagTokens[0]].append(line)

def getlinenos(page ):
anyOpenTag.setP arseAction(tall yTagLineNumber)
anyOpenTag.sear chString(page.l ower()) # changing the entire string to
lower case to get INPUT
tagnames = sorted(tagLocs. keys())
taglinedict={}
for t in tagnames:
taglinedict[t]= unique(tagLocs[t])
return taglinedict
Dec 13 '07 #3

Hi Paul,
I am cross posting the same to grab your attention at pyparsing forums
too. 1000 apologies on the same count!

I am a complete newbie to parsing and totally new to pyparsing.

I have adapted your code to store the line numbers as below.
Surprisingly, the line numbers printed, when I scrap some of the URLs,
is not accurate and is kind of way off.

page = urlli2b.urlopen ("www.....com). read()

def tallyTagLineNum ber(strg, locn, tagTokens):
line = lineno(locn,str g)
tagLocs[tagTokens[0]].append(line)

def getlinenos(page ):
anyOpenTag.setP arseAction(tall yTagLineNumber)
anyOpenTag.sear chString(page.l ower()) # changing the entire
string to lowercase, to grab
# input and INPUT from html as input tag ONLy

tagnames = sorted(tagLocs. keys())
taglinedict={}
for t in tagnames:
taglinedict[t]= unique(tagLocs[t])
return taglinedict
What did I do wrong and why this problem!

Ramdas
Dec 13 '07 #4
On Dec 13, 9:01 am, Ramdas <ram...@gmail.c omwrote:
Hi Paul,

I am cross posting the same to grab your attention at pyparsing forums
too. 1000 apologies on the same count!

I am a complete newbie to parsing and totally new to pyparsing.

I have adapted your code to store the line numbers as below.
Surprisingly, the line numbers printed, when I scrap some of the URLs,
is not accurate and is kind of way off.
<snip>

Ramdas -

You will have to send me that URL off-list using e-mail, Google Groups
masks it and I can't pull it up. In my example, I used the Yahoo home
page. What is the URL you used, and which tags' results were off?

Just some comments:
- I did a quasi-verification of my results, using a quick-and-dirty re
match. This did not give me the line numbers, but did give me counts
of tag names (if anyone knows how to get the string location of an re
match, this would be the missing link for an alternative solution to
this problem). I added this code after the code I posted earlier:

print "Quick-and-dirty verify using re's"
import re
openTagRe = re.compile("<([^ >/!]+)")

tally2 = defaultdict(int )
for match in openTagRe.finda ll(html):
tally2[match] += 1

for t in tally2.keys():
print t,tally2[t],
if tally2[t] != len(tagLocs[t]):
print "<<<"
else:
print

This crude verifier turned up no mismatches when parsing the Yahoo
home page.

- Could the culprit be your unique function? You did not post the
code for this, so I had to make up my own:

def unique(lst):
return sorted(list(set (lst)))

This does trim some of the line numbers, but I did not try to validate
this.

- In your getlinenos function, it is not necessary to call
setParseAction every time. You only need to do this once, probably
right after you define the tallyTagLineNum ber function.

- Here is an abbreviated form of getlinenos:

def getlinenos(page ):
# clear out tally dict, so as not to get crossover data from
# a previously-parsed page
tagLocs.clear()
anyOpenTag.sear chString(page)
return dict((k,unique( v)) for k,v in tagLocs.items() )

If you wanted, you could even inline the unique logic, without too
much obfuscation.

-- Paul
Dec 13 '07 #5
Ramdas wrote:
I am doing some HTML scrapping for a side project.

I need a method using sgmllib or HTMLParser to parse an HTML file and
get line nos of all the tags
Try lxml.html, it provides line numbers for each element.

http://codespeak.net/lxml/dev/

Stefan
Dec 14 '07 #6

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

Similar topics

4
6949
by: lecichy | last post by:
Hello Heres the situation: I got a file with lines like: name:second_name:somenumber:otherinfo etc with different values between colons ( just like passwd file) What I want is to extract some part of it like all names or numbers from each line, simply text fom between e.g. second and third colon. And turn it
3
2600
by: Ponder | last post by:
Okay here's the scenario: I have two big lists of numbers. One number on each line (they're telephone numbers if that helps.) What I want to do, is have VB search through list2.txt for numbers that are also in list1.txt and delete them. I would usually sit and figure this out myself but I have the flu and I know how helpfull you guys are :P~ Thanks in advance to anyone that can help.
2
3162
by: rivka.howley | last post by:
I wrote some code that creates a table with a date/time field at 15-minute intervals. Here's how I create and populate the table With tblDataTemp ..Fields.Append .CreateField("CT_ID", dbLong) ..Fields.Append .CreateField(strTmpIDFld, dbLong) ..Fields.Append .CreateField(strTmpDateFld, dbDate) ..Fields.Append .CreateField(strTmpDataFld, dbDouble)
10
7020
by: Dixie | last post by:
I need to delete some relationships in code. How do I know what the names of those relationships are?
3
2933
by: Jim Bancroft | last post by:
Hi all, In VB6 I used a 3rd party tool for line numbering my source code, to help with debugging. However, in experimenting with VB .Net I've noticed that my exceptions automatically provide line numbers, with no effort required from me. Is this a standard offering in .Net, or is rolling your own line numbers still the way to go? Also, my components at the moment are being compiled in debug mode. Will line numbers still be available...
13
2003
by: athiane | last post by:
I want a way to parse out all function names that appear in a couple of C files. When the parsing logic finds a function name in a file, it should print out the Function name, line number and file in which the Function was found. What approach should i follow to tackle this problem ? Is there any option in the gcc compiler that prints out this information ?
19
8581
by: ramu | last post by:
Hi, I have, suppose 1000 numbers, in a file. I have to find out 5 largest numbers among them without sorting. Can you please give me an efficient idea to do this? My idea is to put those numbers into a binary tree and to find the largest numbers. How else can we do it? Regards
12
3398
by: e271828 | last post by:
Hi, I'm helping to work a developer tool that verifies a given HTML element has a given attribute (e.g., that all LABEL elements have a FOR attribute, all INPUT elements have an ID attribute, etc.). Pretty much all of the functionality is working except a feature that shows in which line of the HTML source a violation of the user-set rule occurs (e.g., where a LABEL element doesn't have a FOR attribute). There doesn't seem to be a...
3
1468
by: nightmare2000 | last post by:
i have an input file with a set of numbers (number per line) , the numbers must include 0 followed by a line that specifies specifies the value of the sum. example of input file: 5 1 4 3 7 9
0
8678
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
8609
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,...
0
9166
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8899
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,...
1
6525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4371
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...
0
4621
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2333
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.