我想使用 Django 创建一个简单的(一页)Web 应用程序,并查看来自 alexa.com/topsites/global 的前 20 个网站。该页面应呈现一个包含 21 行(1 个标题和 20 个网站)和 3 列(排名、网站和描述)的表格。
我使用 django 的知识有限,如果可能的话,我真的需要一些帮助。
我已经使用模板通过一些引导程序创建了一个表,但我实际上不知道如何解析:排名/网站名称/和描述。
有人可以通过一些有用的网站/代码片段引导我走向正确的方向吗?
我知道我必须使用HTMLParser
和实现类似的东西:
from HTMLParser import HTMLParser
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print "Encountered a start tag:", tag
def handle_endtag(self, tag):
print "Encountered an end tag :", tag
def handle_data(self, data):
print "Encountered some data :", data
# instantiate the parser and fed it some HTML
parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
'<body><h1>Parse me!</h1></body></html>')
但我不知道如何在我的应用程序中使用它。
所以,我回来更新。我试过这样做(只是为了打印结果,看看我是否得到了我想要的)但我只得到了一些链接。
有什么帮助吗?
import urllib2, HTMLParser
class MyHTMLParser(HTMLParser.HTMLParser):
def reset(self):
HTMLParser.HTMLParser.reset(self)
#count div to get the rank of website
self.in_count_div = False
#description div to get description of website
self.in_description_div = False
#a tag to get the url
self.in_link_a = False
self.count_items = None
self.a_link_items = None
self.description_items = None
def handle_starttag(self, tag, attrs):
if tag == 'div':
if('class', 'count') in attrs:
self.in_count_div = True
if tag == 'a':
for name, value in attrs:
if name == 'href':
self.a_link_items = [value,'']
self.in_link_a = True
break
if tag == 'div':
if('class', 'description') in attrs:
self.in_description_div = True
#handle data for each section
def handle_data_count(self, data):
if self.in_count_div:
self.count_items[1] += data
def handle_data_url(self, data):
if self.in_link_a:
self.a_link_items[1] += data
def handle_data_description(self, data):
if self.in_description_div:
self.description_items[1] += data
#endtag
def handle_endtag(self, tag):
if tag =='div':
if self.count_items is not None:
print self.count_items
self.count_items = None
self.in_count_div = False
if tag =='a':
if self.a_link_items is not None:
print self.a_link_items
self.a_link_items = None
self.in_link_a = False
if __name__ == '__main__':
myhtml = MyHTMLParser()
myhtml.feed(urllib2.urlopen('http://www.alexa.com/topsites/global').read())