- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathamazon.py
More file actions
Latest commit
71 lines (64 loc) · 2.86 KB
/
Copy pathamazon.py
File metadata and controls
71 lines (64 loc) · 2.86 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
59
60
61
62
63
64
65
66
67
68
69
70
71
# -*- coding: utf-8 -*-
fromseleniumimportwebdriver
frombs4importBeautifulSoup
importos, sys, time, random
importrequests, json, csv
fromdatetimeimportdatetime
classAmazonHelper():
nlist= []
plist= []
def__init__(self):
self.main_url="https://www.amazon.in/s?k=shirts&ref=nb_sb_noss_2"
self.driver=webdriver.Chrome(executable_path=r'D:\Software\chromedriver.exe')
self.driver.get(self.main_url)
self.soup=BeautifulSoup(self.driver.page_source)
# method to get Amazon data.
defgetAmazonData(self):
time.sleep(random.randint(5,8))
r2ele=self.soup.find("div", attrs={"class": "s-result-list s-search-results sg-row"})
r2ele1=r2ele.find("div", attrs={"class": "sg-col-4-of-24 sg-col-4-of-12 sg-col-4-of-36 s-result-item sg-col-4-of-28 sg-col-4-of-16 AdHolder sg-col sg-col-4-of-20 sg-col-4-of-32"})
nxtbtn=self.driver.find_element_by_xpath("//*[@id='search']/div[1]/div[2]/div/span[7]/div/div/div/ul/li[7]/a")
try:
while(nxtbtn):
while(r2ele1):
name=r2ele1.find("span", attrs={"class": "a-size-base-plus a-color-base a-text-normal"}).text
price=r2ele1.find("span", attrs={"class": "a-price-whole"}).text
if(nameandprice):
print("{} : Rs. {}".format(name,price))
AmazonHelper.nlist.append(name)
AmazonHelper.plist.append(price)
else:
break
r2ele1=r2ele1.next_sibling.next_sibling
nxtbtn=self.driver.find_element_by_xpath("//*[@id='search']/div[1]/div[2]/div/span[7]/div/div/div/ul/li[7]/a")
nxtbtn.click()
finally:
self.driver.close()
nl, pl=AmazonHelper.nlist, AmazonHelper.plist
returnnl, pl
# method to write csv file.
defwriteCSV(self, nl, pl):
try:
withopen("amazon.csv", mode='a') ascsv_file:
fieldnames= ["Name", "Price"]
writer=csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
fori,jinzip(nl, pl):
writer.writerow(
{
'Name': i, 'Price': j
}
)
csv_file.close()
print("File written successfully.")
except:
print("Error occured during written file.")
print(sys.exc_info())
# method to start process.
defstart(self):
nl, pl=self.getAmazonData()
self.writeCSV(nl, pl)
if__name__=="__main__":
# objTH is an instance for AmazonHelper.
objTH=AmazonHelper()
objTH.start()