Discuss / Python / 交作业

交作业

Topic source
from html.parser import HTMLParser
from urllib.request import urlopen
from contextlib import closing

class MyHTMLParser(HTMLParser):
    def __init__(self):
        self.time = []
        self.location = []
        self.title = []
        self.sign = ''
        self.isShow = False
        super().__init__()

    def handle_starttag(self, tag, attrs):
        if attrs:
            if attrs[0][1] == 'event-title':
                self.sign = 'title'
            elif tag == 'time':
                self.sign = 'time'
            elif attrs[0][1] == 'event-location':
                self.sign = 'location'

    def handle_data(self, data):
        if data == 'Upcoming Events':
            self.isShow = True
        elif data == 'You just missed...':
            self.isShow = False
        if self.sign == 'time' and self.isShow:
            self.time.append(data)
            self.sign = ''
        elif self.sign == 'location' and self.isShow:
            self.location.append(data)
            self.sign = ''
        elif self.sign == 'title' and self.isShow:
            self.title.append(data)
            self.sign = ''

parser = MyHTMLParser()
with closing(urlopen('https://www.python.org/events/python-events/')) as page:
    for line in page:
        parser.feed(str(line))

for i in range(len(parser.time)):
    print('-------------------------------------')
    print('地点:%s\n时间:%s\n主题:%s'% (parser.location[i],parser.time[i],parser.title[i]))
    if i == len(parser.time)-1:
        print('-------------------------------------')

默_kk

#2 Created at ... [Delete] [Delete and Lock User]

你的答案很棒,对我很有帮助,不过我觉得

print('-------------------------------------')

可以用下面的方式来写

print('-' * 50)

另外,

self.sign = ''

可以只在函数的最后一行写一次:

if self.sign == 'time' and self.isShow:
    self.time.append(data)
elif self.sign == 'location' and self.isShow:
    self.location.append(data)
elif self.sign == 'title' and self.isShow:
    self.title.append(data)
self.sign = ''

Jessica9186

#3 Created at ... [Delete] [Delete and Lock User]

您好,看了您的代码稍微明白了一点,但是运行完了之后location是空的,不知道问题出在哪儿了,不知道能不能解释下?谢谢


  • 1

Reply