|
| 1 | +import requests |
| 2 | +from bs4 import BeautifulSoup |
| 3 | +import pandas as pd |
| 4 | +import random |
| 5 | +import numpy as np |
| 6 | +import itertools |
| 7 | +import time |
| 8 | + |
| 9 | + |
| 10 | +class Scrap: |
| 11 | + |
| 12 | + def __init__(self, urls_dict, start_date='2020-01-01', end_date='2020-08-01', number=10, year=2020): |
| 13 | + self.urls = urls_dict |
| 14 | + self.start = pd.to_datetime(start_date) |
| 15 | + self.end = pd.to_datetime(end_date) |
| 16 | + self.n = number |
| 17 | + self.year = year |
| 18 | + self.titles = [] |
| 19 | + self.sub_titles = [] |
| 20 | + self.article_link = [] |
| 21 | + self.claps = [] |
| 22 | + self.reading_time = [] |
| 23 | + self.responses = [] |
| 24 | + self.pubs = [] |
| 25 | + self.dates_list = [] |
| 26 | + |
| 27 | + def randDates(self): |
| 28 | + start_u = self.start.value//10**9 |
| 29 | + end_u = self.end.value//10**9 |
| 30 | + |
| 31 | + return pd.DatetimeIndex((10**9*np.random.randint(start_u, end_u, self.n, dtype=np.int64)).view('M8[ns]')).date |
| 32 | + |
| 33 | + def scrap(self): |
| 34 | + dates = pd.to_datetime(pd.Series(self.randDates())) |
| 35 | + for i in range(len(dates)): |
| 36 | + month = dates.dt.month[i] |
| 37 | + day = dates.dt.day[i] |
| 38 | + for publication, url in self.urls.items(): |
| 39 | + url = url+'/archive/{0}/{1:02d}/{2:02d}' |
| 40 | + print(f'Publication: {publication}, Date: {self.year}-{month}-{day}') |
| 41 | + response = requests.get(url.format(self.year, month, day), allow_redirects=True) |
| 42 | + if not response.url.startswith(url.format(self.year, month, day)): |
| 43 | + continue |
| 44 | + page = response.content |
| 45 | + soup = BeautifulSoup(page, 'html.parser') |
| 46 | + articles = soup.find_all("div", class_="postArticle postArticle--short js-postArticle js-trackPostPresentation js-trackPostScrolls") |
| 47 | + |
| 48 | + number = len([i.find('h3',class_="graf--title" ).text if i.find('h3',class_="graf--title" ) is not None else '' for i in articles]) |
| 49 | + |
| 50 | + self.titles.append([i.find('h3',class_="graf--title" ).text if i.find('h3',class_="graf--title" ) is not None else '' for i in articles]) |
| 51 | + |
| 52 | + self.sub_titles.append([i.find("h4", class_="graf--subtitle").text if i.find("h4", class_="graf--subtitle") is not None else '' for i in articles]) |
| 53 | + |
| 54 | + self.article_link.append([i.find_all('a')[3]['href'].split('?')[0] for i in articles]) |
| 55 | + |
| 56 | + self.claps.append([0 if (k is None) or (k == '') or (k.split is None) else int(float(k.split('K')[0])*1000) if len(k.split('K'))==2 else int(float(k.split('K')[0])) for k in [j.text for j in [i.find_all('button')[1] for i in articles]]]) |
| 57 | + |
| 58 | + self.reading_time.append([int(i.find("span", class_="readingTime")['title'].split()[0]) if i.find("span", class_="readingTime") is not None else 0 for i in articles]) |
| 59 | + |
| 60 | + self.responses.append([i.find_all('a')[6].text.split(' ')[0] if (len(i.find_all('a'))==7) and len(i.find_all('a')[6].text.split(' '))!=0 else 0 for i in articles]) |
| 61 | + |
| 62 | + self.pubs.append([publication]*number) |
| 63 | + |
| 64 | + self.dates_list.append([f'{self.year}-{month}-{day}']) |
| 65 | + |
| 66 | + time.sleep(0.3) |
| 67 | + |
| 68 | + def dataframe(self): |
| 69 | + columns = ['Title', 'SubTitle', 'Link', 'Claps', 'Reading_Time', 'Responses', 'Publication','Date_Published'] |
| 70 | + titles = list(itertools.chain.from_iterable(self.titles)) |
| 71 | + sub_titles = list(itertools.chain.from_iterable(self.sub_titles)) |
| 72 | + article_link = list(itertools.chain.from_iterable(self.article_link)) |
| 73 | + claps = list(itertools.chain.from_iterable(self.claps)) |
| 74 | + reading_time = list(itertools.chain.from_iterable(self.reading_time)) |
| 75 | + responses = list(itertools.chain.from_iterable(self.responses)) |
| 76 | + pubs = list(itertools.chain.from_iterable(self.pubs)) |
| 77 | + dates = list(itertools.chain.from_iterable(self.dates_list)) |
| 78 | + |
| 79 | + return pd.DataFrame(zip(titles, sub_titles, article_link, claps, reading_time, responses, pubs, dates), columns=columns) |
0 commit comments