File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ import requests
2
+ from bs4 import BeautifulSoup as bs4
3
+ import csv
4
+
5
+
6
+
7
+ def request_maker ():
8
+ headers = {
9
+ 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
10
+ }
11
+ url = 'https://books.toscrape.com/index.html'
12
+ res = requests .get (url , headers = headers )
13
+ soup = bs4 (res .content , 'html5lib' )
14
+ return soup
15
+
16
+ def finder (soup ):
17
+ books = []
18
+ prices = []
19
+ h3 = soup .find_all ('h3' )
20
+ price_tags = soup .find_all ('p' , class_ = 'price_color' )
21
+
22
+ for price_tag in price_tags :
23
+ price = price_tag .text .strip ()
24
+ prices .append (price )
25
+
26
+ for book in h3 :
27
+ i = book .find ('a' ).get ('title' )
28
+ books .append (i )
29
+ return books ,prices
30
+
31
+ def csv_maker (data ):
32
+ books ,prices = data
33
+ file_name = 'book_data.csv'
34
+ with open (file_name ,'w' ) as csv_file :
35
+ writer = csv .writer (csv_file )
36
+ writer .writerow (['Title' , 'Price' ])
37
+ for i in range (0 ,len (books )):
38
+ writer .writerow ([books [i ],prices [i ]])
39
+ print ("csv file generated successfully, saved as book_data.csv" )
40
+
41
+
42
+ def main ():
43
+ soup = request_maker ()
44
+ data = finder (soup )
45
+ csv_maker (data )
46
+
47
+ if __name__ == '__main__' :
48
+ main ()
You can’t perform that action at this time.
0 commit comments