473,770 Members | 7,229 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Parsing an HTML a tag

How can I parse an HTML file and collect only that the A tags. I have a
start for the code but an unable to figure out how to finish the code.
HTML_parse gets the data from the URL document. Thanks for the help

def HTML_parse(data ):
from HTMLParser import HTMLParser
parser = MyHTMLParser()

parser.feed(dat a)

class MyHTMLParser(HT MLParser):

def handle_starttag (self, tag, attrs):

def handle_endtag(s elf, tag):

def read_page(URL):
"this function returns the entire content of the specified URL
document"
import urllib
connect = urllib.urlopen( url)
data = connect.read()
connect.close()
return data

Sep 24 '05
10 2702

"George" <bu*******@hotm ail.com> wrote:
I'm very new to python and I have tried to read the tutorials but I am
unable to understand exactly how I must do this problem.

Specifically, the showIPnums function takes a URL as input, calls the
read_page(url) function to obtain the entire page for that URL, and
then lists, in sorted order, the IP addresses implied in the "<A
HREF=· · ·>" tags within that page.
"""
Module to print IP addresses of tags in web file containing HTML
showIPnums('htt p://22c118.cs.uiowa .edu/uploads/easy.html') ['0.0.0.0', '128.255.44.134 ', '128.255.45.54']
showIPnums('htt p://22c118.cs.uiowa .edu/uploads/pytorg.html') ['0.0.0.0', '128.255.135.49 ', '128.255.244.57 ', '128.255.30.11' ,
'128.255.34.132 ', '128.255.44.51' , '128.255.45.53' ,
'128.255.45.54' , '129.255.241.42 ', '64.202.167.129 ']

"""

def read_page(url):
import formatter
import htmllib
import urllib

htmlp = htmllib.HTMLPar ser(formatter.N ullFormatter())
htmlp.feed(urll ib.urlopen(url) .read())
htmlp.close()

def showIPnums(URL) :
page=read_page( URL)

if __name__ == '__main__':
import doctest, sys
doctest.testmod (sys.modules[__name__])

You forgot to mention that you don't want duplicates in the result. Here's a function that passes
the doctest:

from urllib import urlopen
from urlparse import urlsplit
from socket import gethostbyname
from BeautifulSoup import BeautifulSoup

def showIPnums(url) :
"""Return the unique IPs found in the anchors of the webpage at the given
url.
showIPnums('htt p://22c118.cs.uiowa .edu/uploads/easy.html') ['0.0.0.0', '128.255.44.134 ', '128.255.45.54'] showIPnums('htt p://22c118.cs.uiowa .edu/uploads/pytorg.html')

['0.0.0.0', '128.255.135.49 ', '128.255.244.57 ', '128.255.30.11' , '128.255.34.132 ',
'128.255.44.51' , '128.255.45.53' , '128.255.45.54' , '129.255.241.42 ', '64.202.167.129 ']
"""
hrefs = set()
for link in BeautifulSoup(u rlopen(url)).fe tch('a'):
try: hrefs.add(getho stbyname(urlspl it(link["href"])[1]))
except: pass
return sorted(hrefs)
HTH,
George
Sep 25 '05 #11

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

Similar topics

8
9445
by: Gerrit Holl | last post by:
Posted with permission from the author. I have some comments on this PEP, see the (coming) followup to this message. PEP: 321 Title: Date/Time Parsing and Formatting Version: $Revision: 1.3 $ Last-Modified: $Date: 2003/10/28 19:48:44 $ Author: A.M. Kuchling <amk@amk.ca> Status: Draft Type: Standards Track
14
2638
by: Viktor Rosenfeld | last post by:
Hi, I need to create a parser for a Python project, and I'd like to use process kinda like lex/yacc. I've looked at various parsing packages online, but didn't find anything useful for me: - PyLR seems promising but is for Python 1.5 - Yappy seems promising, but I couldn't get it to work. It doesn't even compile the main example in it's documentation - mxTexttools is way complicated. I'd like something that I can give a BNF
9
2917
by: RiGGa | last post by:
Hi, I want to parse a web page in Python and have it write certain values out to a mysql database. I really dont know where to start with parsing the html code ( I can work out the database part ). I have had a look at htmllib but I need more info. Can anyone point me in the right direction , a tutorial or something would be great. Many thanks
0
1583
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.
3
3660
by: Willem Ligtenberg | last post by:
I decided to use SAX to parse my xml file. But the parser crashes on: File "/usr/lib/python2.3/site-packages/_xmlplus/sax/handler.py", line 38, in fatalError raise exception xml.sax._exceptions.SAXParseException: NCBI_Entrezgene.dtd:8:0: error in processing external entity reference This is caused by: <!DOCTYPE Entrezgene-Set PUBLIC "-//NCBI//NCBI Entrezgene/EN" "NCBI_Entrezgene.dtd">
16
2906
by: Terry | last post by:
Hi, This is a newbie's question. I want to preload 4 images and only when all 4 images has been loaded into browser's cache, I want to start a slideshow() function. If images are not completed loaded into cache, the slideshow doesn't look very nice. I am not sure how/when to call the slideshow() function to make sure it starts after the preload has been completed.
1
2427
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.
4
4865
by: Rick Walsh | last post by:
I have an HTML table in the following format: <table> <tr><td>Header 1</td><td>Header 2</td></tr> <tr><td>1</td><td>2</td></tr> <tr><td>3</td><td>4</td></tr> <tr><td>5</td><td>6</td></tr> </table> With an XSLT styles sheet, I can use for-each to grab the values in
9
4062
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.)....
4
6842
by: Neil.Smith | last post by:
I can't seem to find any references to this, but here goes: In there anyway to parse an html/aspx file within an asp.net application to gather a collection of controls in the file. For instance what I'm trying to do is upload a html file onto the web server, convert it to aspx file and then parse it for input tags/controls, which in turn will become fields in a newly created database table. Clearly when the aspx file is called the...
0
9592
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
9425
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
10004
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
9870
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
6678
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
5313
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...
1
3972
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2817
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.