-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_crawler_csv.py
More file actions
58 lines (46 loc) · 1.97 KB
/
Copy pathtest_crawler_csv.py
File metadata and controls
58 lines (46 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import csv
import time
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
# define a class with variables for the single elements
class CrawledArticle():
def __init__(self, title, emoji, content, image):
self.title = title
self.emoji = emoji
self.content = content
self.image = image
# define a class to fetch the page, parse the content, assign it to the variables and put it in a list
class ArticleFetcher():
def fetch(self):
url = "http://python.beispiel.programmierenlernen.io/index.php"
articles = []
while url != " ":
print(url)
# hold on for second to avoid trouble on the server in case something is going wrong
time.sleep(1)
r = requests.get(url)
doc = BeautifulSoup(r.text, "html.parser")
# extracting the elements of all article and store it in a list
for card in doc.select(".card"):
emoji = card.select_one(".emoji").text
content = card.select_one(".card-text").text
title = card.select(".card-title span")[1].text
image = urljoin(url, card.select_one("img").attrs["src"])
crawled = CrawledArticle(title, emoji, content, image)
articles.append(crawled)
button = doc.select_one(".navigation .btn")
# as long as there's a next page button, pass the url into the loop
if button:
next_page = urljoin(url, button.attrs["href"])
url = next_page
else:
url = " "
return articles
# fetch all articles from the url
fetcher = ArticleFetcher()
# save all articles in a csv file
with open("./data/crawler.csv", "w", newline='') as file:
linewriter = csv.writer(file, delimiter = ";", quotechar = " ")
for a in fetcher.fetch():
linewriter.writerow([a.emoji, a.title, a.content, a.image])