Discuss / Python / 还是BeautifulSoup比较方便

还是BeautifulSoup比较方便

Topic source

javaape

#1 Created at ... [Delete] [Delete and Lock User]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
import requests


class Event(object):
    def __init__(self, title='', time='', location=''):
        self.title = title
        self.time = time
        self.location = location

    def __repr__(self):
        return '会议主题: %s, 时间: %s, 地点:%s' % (self.title, self.time, self.location)


def getEvents(htmlText):
    events = []
    soup = BeautifulSoup(req.text, "html.parser")
    eventsUl = soup.find('ul', attrs={'class': 'list-recent-events menu'})
    for li in eventsUl.find_all('li'):
        event = Event()
        event.title = li.h3.a.string
        event.time = next(li.p.time.children)
        event.location = li.find('span', attrs={'class': 'event-location'}).string
        events.append(event)
    return events


req = requests.get(r'https://www.python.org/events/python-events/')
events = getEvents(req.text)
for event in events:
    print(event)

  • 1

Reply