Discuss / Python / 作业

作业

Topic source
from html.parser import HTMLParser
from urllib import request

with request.urlopen('https://www.python.org/events/python-events/') as f:
    html = f.read().decode('utf-8')


class MyHTMLParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.flag = ''
        self.info = []

    def handle_starttag(self, tag, attrs):
        if not attrs: return        
        atr = attrs[0][1]
        if atr == 'event-title':
            self.flag = 'title'        
        elif tag == 'time':
            if atr == 'say-no-more':
                self.flag = 'year'            
            elif attrs[0][0] == 'datetime':
                self.flag = 'date'        
        elif atr == 'event-location':
            self.flag = 'location' 
   
    def handle_endtag(self, tag):
        self.flag = ''    

    def handle_data(self, data):
        if self.flag == 'title':
            self.info.append(f'会议名称:{data}')
        elif self.flag == 'year':
            self.info.append(f'会议年份:{data.strip()}')
        elif self.flag == 'date':
            self.info.append(f'会议时间:{data}')
        elif self.flag == 'location':
            self.info.append(f'会议地点:{data} \n')

parser = MyHTMLParser()
parser.feed(html)
for n in parser.info:
    print(n)

'''
----------结果-----------
会议名称:PyCon Somalia 2023
会议时间:27 Dec. – 28 Dec. 
会议时间: 2023
会议地点:Mogadishu, Somalia 

会议名称:Building Python Communities Around Python for Kids
会议时间:10 Jan.
会议时间: 2024
会议地点:MountainHub, Top floor 1st Trust Building, Great Soppo, Buea, Cameroon 

会议名称:FOSDEM 2024: Python Devroom
会议时间:04 Feb.
会议时间: 2024
会议地点:Brussels, Belgium 

会议名称:Python Devroom @ FOSDEM 2024
会议时间:04 Feb.
会议时间: 2024
会议地点:Brussels, Belgium 

会议名称:Prague Python Pizza 2024
会议时间:24 Feb.
会议时间: 2024
会议地点:Prague, Czech Republic 

会议名称:PyCon Namibia 2024 
会议时间:04 March – 07 March 
会议时间: 2024
会议地点:Windhoek, Namibia 

会议名称:FlaskCon 2023
会议时间:16 Dec. – 17 Dec. 
会议时间: 2023
会议地点:Online 

会议名称:PyCon Thailand 2023
会议时间:15 Dec. – 16 Dec. 
会议时间: 2023
会议地点:Bangkok, Thailand 
'''

  • 1

Reply