import requests
from bs4 import BeautifulSoup
import re


def cal(soup):
    global thebestOne_count
    global thebestOne_name
    global Sum_count

    div_article = soup.find('div', attrs={'class': "balist"})
    divs = div_article.find_all('li', attrs={'class': "even"})
    for d in divs:
        co = int(re.search('\d+', d.find('li', attrs={'class': "view-num"}).text).group())
        if co > thebestOne_count:
            h4 = d.find('h4').text.replace('\n', '').replace('  ', '')
            thebestOne_name = h4
            thebestOne_count = co
        Sum_count += co


def main(url):
    global date

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'
    }
    res = requests.get(url, headers=headers)

    soup = BeautifulSoup(res.text, 'lxml')

    try:
        a = soup.find(
            'aside'
        ).find('ul', attrs={'class': 'archive-list'}).find('a')
        date = list(filter(lambda x: x and x != '\n', a.text.split(' ')))[0]
        href = a['href']
    except Exception as e:
        print('[Error]', e.args)
    else:

        res = requests.get(href, headers=headers)
        soup = BeautifulSoup(res.text, 'lxml')
        ids = soup.find('div', attrs={'id': 'pageBox'})
        ids_string = str(ids)
        data = re.findall('data-page="(\d+)"', ids_string)

        cal(soup)
        if data:
            data = data[1:]
            for d in data:
                newhref = href + d + '?'
                res = requests.get(newhref, headers=headers)
                soup = BeautifulSoup(res.text, 'lxml')
                cal(soup)


if __name__ == '__main__':
    Sum_count = 0
    thebestOne_name = ''
    thebestOne_count = 0
    date = ''
    url = 'http://guba.eastmoney.com/jj.html'
    main(url)
    print('In [date]: %s' % date, thebestOne_name, '\nIts count is %d' % thebestOne_count)
    print('The Sum of all the article is %d' % Sum_count)
