Загрузка...

Парсер парсит с каждой страницы по одному товару

Тема в разделе Python создана пользователем hoholmostwanted 11 май 2020. 281 просмотр

  1. hoholmostwanted
    hoholmostwanted Автор темы 11 май 2020 Заблокирован(а) 35 1 ноя 2019
    Вероятно вопрос найтупеший, но всё же. Задумано было так, парсер должен спарсить все ноутбуки из раздела 'ноутбуки', видимо я что-то где-то напутал, но парсит он то только первый товар, на каждой странице. Подскажите пожалуйста как это исправить.
    Ссылка - https://prom.ua/Noutbuki (не реклама)
    Код
    import requests
    from bs4 import BeautifulSoup

    def get_html(url):
    r = requests.get(url)
    if r.ok:
    return r.text
    print(r.status_code)

    def get_page(html):
    soup = BeautifulSoup(html, 'lxml')
    notebooks = soup.find('div', class_='x-gallery-tile js-gallery-tile js-productad x-gallery-tile_type_click').find_all('div', class_='x-gallery-tile__content')
    #Получил контейнер с ноутбуками
    for notebook in notebooks:
    try:
    price = notebook.find('div', class_='x-gallery-tile__price-holder').find('span', class_='x-gallery-tile__price-counter').text # цена
    except:
    price = ''
    try:
    name = notebook.find('span', class_='ek-link ek-link_style_multi-line').text # название ноутбука
    except:
    name = ''
    try:
    link = soup.find('a', class_='x-gallery-tile__tile-link').get('href') # ссылка на товар
    except:
    link = ''
    print(price + ' | ' + name + ' | ' + link)
    with open('parsed.txt', 'a') as text_write: # создаётся файл, в который будут добавляться данные которые мы передаём в переменную text_write, методом .write()
    text_write.write(price + ' | ' + name + ' | ' + link + '\n')

    print(len(notebooks))


    def main():
    pattern = 'https://prom.ua/Noutbuki;{}'
    for i in range(0, 207):
    url = pattern.format(str(i))
    get_page(get_html(url))

    if __name__ == '__main__':
    main()
     
  2. VRT3R
    VRT3R 11 май 2020 продам гараж 347 24 сен 2018
    Что получает параметр notebooks? Количество?
     
    1. hoholmostwanted Автор темы
      VRT3R, да, все контейнеры с ноутбуками, если это можно так назвать
  3. Vercello
    Vercello 11 май 2020 525 20 июн 2017
    1. hoholmostwanted Автор темы
      Vercello, честно сейчас нет времени и настроения читать и изучать материал, если можешь просто укажи на ошибку :)
  4. Decoy4298
    Decoy4298 11 май 2020 217 18 фев 2020
    Python
    notebooks = soup.find('div', class_='x-gallery-tile js-gallery-tile js-productad x-gallery-tile_type_click').find_all('div', class_='x-gallery-tile__content')
    через soup.find ты найдёшь только один ноутбук, find_all юзай
     
    1. Посмотреть предыдущие комментарии (1)
    2. Decoy4298
      hoholmostwanted, ну блть, одной этой поправкой твой код не пофикстится
      Python
      import requests
      from bs4 import BeautifulSoup


      def get_html(url):
      r = requests.get(url)
      if r.ok:
      return r.text
      print(r.status_code)


      def get_page(html):
      soup = BeautifulSoup(html, 'lxml')
      notebooks = soup.find_all('div', class_='x-gallery-tile js-gallery-tile js-productad x-gallery-tile_type_click')

      # Получил контейнер с ноутбуками
      for notebook in notebooks:
      notebook = notebook.find('div', class_='x-gallery-tile__content')
      try:
      price = notebook.find('div', class_='x-gallery-tile__price-holder').find('span', class_='x-gallery-tile__price-counter').text # цена
      except:
      price = ''
      try:
      # название ноутбука
      name = notebook.find('span', class_='ek-link ek-link_style_multi-line').text
      except:
      name = ''
      try:
      # ссылка на товар
      link = soup.find('a', class_='x-gallery-tile__tile-link').get('href')
      except:
      link = ''
      print(price + ' | ' + name + ' | ' + link)
      with open('parsed.txt', 'a') as text_write:
      text_write.write(price + ' | ' + name + ' | ' + link + '\n')

      print(len(notebooks))


      def main():
      pattern = 'https://prom.ua/Noutbuki;{}'
      for i in range(0, 207):
      url = pattern.format(i)
      get_page(get_html(url))


      if __name__ == '__main__':
      main()
    3. hoholmostwanted Автор темы
      Decoy4298, я это понимаю, можешь указать на ошибку?В этом коде:
      Python
      import requests
      from bs4 import BeautifulSoup

      def get_html(url):
      r = requests.get(url)
      if r.ok:
      return r.text
      print(r.status_code)

      def get_page(html):
      soup = BeautifulSoup(html, 'lxml')
      notebooks = soup.find_all('div', class_='x-gallery-tile js-gallery-tile js-productad x-gallery-tile_type_click').find('div', class_='x-gallery-tile__content')
      #Получил контейнер с ноутбуками
      for notebook in notebooks:
      try:
      price = notebook.find('div', class_='x-gallery-tile__price-holder').find('span', class_='x-gallery-tile__price-counter').text # цена
      except:
      price = ''
      try:
      name = notebook.find('span', class_='ek-link ek-link_style_multi-line').text # название ноутбука
      except:
      name = ''
      #print(price + ' | ' + name + ' | ' + link)
      with open('parsed.txt', 'a') as text_write: # создаётся файл, в который будут добавляться данные которые мы передаём в переменную text_write, методом .write()
      text_write.write(price + ' | ' + name + ' | ' + '\n')

      print(len(notebooks))


      def main():
      pattern = 'https://prom.ua/Noutbuki;{}'
      for i in range(0, 207):
      url = pattern.format(str(i))
      get_page(get_html(url))

      if __name__ == '__main__':
      main()
    4. Decoy4298
      hoholmostwanted, я тебе уже исправленный кинул, сравни и всё...
      div с классом x-gallery-tile js-gallery-tile js-productad x-gallery-tile_type_click -- это КАЖДЫЙ ОТДЕЛЬНЫЙ ноутбук, а не тег, в котором все ноутбуки находятся, тебе сначала нужно найти все элементы по этому паттерну, чтоб получить список плиток с товарами, а потом уже в каждой плитке искать span с нужным классом, а мб вообще можно сразу найти спаны и всё, я не проверял.
    5. Посмотреть следующие комментарии (1)
Top
Загрузка...