Created
August 15, 2018 12:28
-
-
Save kirussian911/d16f389a584f18d8ee838bfdc24c56be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib.request # библиотека для работы с сетью | |
from bs4 import BeautifulSoup # библиотека для парсинга html | |
import csv | |
''' | |
1. Товары с пустой ценой | |
2. Лишние строки | |
3. Лишние символы [ ] ' | |
4. В идеале и разместить сразу в разных столбцах | |
5. Парсинг картинок через import shutil | |
6. Сохранение картинок в отдельную папку через import os | |
7. Добавить проверки отклика сайта и текст в случае ошибок | |
''' | |
BASE_URL = 'https://aliholic.com/shop/' | |
# получаем содержимое страницы | |
def get_html(url): | |
response = urllib.request.urlopen(url) | |
# возвращает содержимое веб-страницы | |
return response.read() | |
def get_page_count(html): | |
soup = BeautifulSoup(html, 'html.parser') | |
paggination = int(soup.find('div', class_='nav-links').find_all('a', class_='page-numbers')[-2].text.replace('Page ', '')) | |
return paggination | |
# функция принимает исходный код страницы | |
def parse(html): | |
# soup позволяет просматривать теги, содержимое и т.п. | |
soup = BeautifulSoup(html) | |
# находим первоначальную форму, где есть все данные | |
table = soup.find('div', {'class':'blog-grid-wrap'}) | |
projects = [] | |
counter = 0 | |
for row in table.find_all('article'): | |
cols = row.find_all('div',{'class':'hentry-middle'}) | |
projects.append({ | |
'title': cols[0].a.text.replace(',', ''), | |
'old_prices':[old_price.text for old_price in cols[0].div.find_all('del')], | |
'price':[price.text for price in cols[0].div.find_all('ins')], | |
'link': [link for link in cols[0].a.find_all('href')] | |
}) | |
return projects | |
def save(projects, path): | |
with open(path, 'w') as csvfile: | |
writer = csv.writer(csvfile) | |
writer.writerow(('Название', 'Старая цена', 'Цена', 'Ссылка')) | |
for project in projects: | |
writer.writerow((project['title'], project['old_prices'], project['price'], project['link'])) | |
def main(): | |
page_count = get_page_count(get_html(BASE_URL)) | |
print('Всего найдено страниц %s' % page_count) | |
projects = [] | |
for page in range(1, 5): | |
print('Парсинг %d%%' % (page /page_count * 100)) | |
projects.extend(parse(get_html(BASE_URL + 'page/%d' % page))) | |
for project in projects: | |
print(project) | |
save(projects, 'aliholic.csv') | |
if __name__=='__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment