Guest User

Untitled

a guest
Sep 12th, 2020
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import csv
  4.  
  5. CSV = 'cards.csv'
  6. HOST = 'https://minfin.com.ua/'
  7. URL = 'https://minfin.com.ua/cards/'
  8. HEADERS = {
  9. 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  10. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
  11. }
  12.  
  13. def get_html(url, params=''):
  14. r = requests.get(url, headers=HEADERS, params=params)
  15. return r
  16.  
  17. def get_content(html):
  18. soup = BeautifulSoup(html, 'html.parser')
  19. items = soup.find_all('div', class_='product-item')
  20. cards = []
  21.  
  22. for item in items:
  23. cards.append(
  24. {
  25. 'title':item.find('div', class_='title').get_text(strip=True),
  26. 'link_product': HOST + item.find('div', class_='title').find('a').get('href'),
  27. 'brand':item.find('div', class_='brand').get_text(strip=True),
  28. 'card_img': HOST + item.find('div', class_='image').find('img').get('src')
  29. }
  30. )
  31. return cards
  32.  
  33. def save_doc(items, path):
  34. with open(path, 'w', newLine='') as file:
  35. writer = csv.writer(file, delimiter='')
  36. writer.writerow(['Название продукта', 'Ссылка на продукт', 'Банк', 'Изображение карты'])
  37. for item in items:
  38. writer.writerow([item['title'], item['link_product'], item['brand'], item['card_img']])
  39.  
  40. def parser():
  41. PAGENATION = input('Количество страниц для парсинга: ')
  42. PAGENATION = int(PAGENATION.strip())
  43. html = get_html(URL)
  44. if html.status_code == 200:
  45. cards = []
  46. for page in range(1, PAGENATION):
  47. print(f'Парсим страницу: {page}')
  48. html = get_html(URL, params={'page': page})
  49. cards.extend(get_content(html.text))
  50. save_doc(cards, CSV)
  51. pass
  52. else:
  53. print('Error')
  54.  
  55. parser()
Add Comment
Please, Sign In to add comment