MikeWP

Untitled

Apr 16th, 2018
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. # https://www.rithmschool.com/blog
  2. # next_page_url = "https://www.rithmschool.com/blog?page=2"
  3. import requests
  4. from bs4 import BeautifulSoup
  5. from csv import writer
  6.  
  7.  
  8. def get_articles(url):
  9.     response = requests.get(url, timeout=30)
  10.     soup = BeautifulSoup(response.text, "html.parser")
  11.     articles = soup.find_all("article")
  12.     for article in articles:
  13.             a_tag = article.find("a")
  14.             title = a_tag.get_text() # title of each article
  15.             url = a_tag["href"] # url adress of each article   
  16.             date = article.find("time")["datetime"] # date of publishing each of the article
  17.             csv_writer.writerow([title, url, date])
  18.  
  19.  
  20. response = requests.get("https://www.rithmschool.com/blog", timeout=30)
  21. soup = BeautifulSoup(response.text, "html.parser")
  22. last_page = soup.find("span", class_="last").find("a")["href"]
  23. site_url = "https://www.rithmschool.com/blog"
  24. l_page_url = site_url[:-5] + last_page
  25. pages_range = range(2, (int(l_page_url[-1])) + 2)
  26. site = "https://www.rithmschool.com/blog"
  27. page_num = 1
  28. new_file = "articles.csv"
  29. print(f"Saving articles from page {page_num}.")
  30. with open(new_file, "a", newline="") as file:
  31.     csv_writer = writer(file)
  32.     csv_writer.writerow(["title", "link", "date"])
  33.     for num in pages_range:
  34.         get_articles(site)
  35.         site = l_page_url[:-1] + str(num)
  36.         page_num += 1
  37.         print(f"Saving articles from page {page_num}.")
  38.     print(f"All of the articles are saved in {new_file}.")
Advertisement
Add Comment
Please, Sign In to add comment