I am learning how to scrape data from a website using Python and Beautiful Soup, what I'm trying to achieve with the code below is to get data from a South African e-commerce website and and save important information such as the image url, price, etc in a array. The code works well but the problem is it's too inconsistent, I have to run the script 3 to 4 times before having the expected result. When I run the script for the first time, most of the time I get an empty array.
I would appreciate if someone can tell me what went wrong in my code or what might cause the issue
def get_items(url):
driver.get(url)
results = []
content = driver.page_source
soup = BeautifulSoup(content, features="lxml")
driver.quit()
for element in soup.find_all(attrs="product-card"):
image = element.find('img')
link = element.find('a', {'class': 'product-link'})
description_element = element.find('h4', {'class': 'product-desc'})
description = description_element.string
price = element.findAll('span', {'class': 'product-price'})
results.append({
'image': image['src'],
'description': description.strip(),
'link': link['href'],
'price': price[0].string,
})
print(results)