Вопрос по скрапингу на Python и BeautifulSoup
Вот код
import requests
from bs4 import BeautifulSoup
def get_html(url):
try:
r = requests.get(url)
return r.text
except Exception as ex:
print('Ошибка в функции get_html()', ex)
def get_data(url, path):
html = get_html(url)
soup = BeautifulSoup(html, 'lxml')
try:
product_name = soup.find('div', class_='main-header').find('h1').text.strip()
except Exception as ex:
product_name = 'Имя товара отсутствует'
print('Имя товара', ex)
try:
quantity1 = soup.find('div', class_='product__extrainfo-row').find('span').find('b').text.strip()
except Exception as ex:
quantity1 = 'Количество отсутствует'
print('Количество1 товара', ex)
try:
price1 = soup.find('span', class_='ordering__value').text.strip()
except Exception as ex:
price1 = 'Цена1 отсутствует'
print('Цена1 товара', ex)
try:
quantity2 = soup.find('div', class_='ordering__discount nw').find('b').text.strip()
except Exception as ex:
quantity2 = 'Количество2 отсутствует'
print('Количество2 товара', ex)
try:
price2 = soup.find('div', class_='ordering__discount nw').find('span', class_='price').text.strip()
except Exception as ex:
price2 = 'Цена2 отсутствует'
print('Цена2 товара', ex)
try:
quantity3 = soup.find_all('div', class_='ordering__discount nw')[-1].find('b').text.strip()
except Exception as ex:
quantity3 = 'Количество3 отсутствует'
print('Количество3 товара', ex)
try:
price3 = soup.find_all('div', class_='ordering__discount nw')[-1].find('span', class_='price').text.strip()
except Exception as ex:
price3 = 'Цена3 отсутствует'
print('Цена3 товара', ex)
try:
descriptions = soup.find('div', class_='showhide item_desc').find_all('p')
description = ''
for part_description in descriptions:
item_description = part_description.text
description += item_description
print(description)
except Exception as ex:
description = ''
try:
product_params = soup.find('table', class_='product__params ptext').find_all('tr')
params = ''
for param in product_params:
name = param.find('td', class_='product__param-name').text
value = param.find('td', class_='product__param-value').find('a').text
param = f' {name} : {value}'
params += param
print(params)
except Exception as ex:
params = ''
def get_block_url(block_name, catalog_header, category_name, item_url):
for page in range(1, 1001):
url = item_url + f'?page={page}'
html = get_html(url)
soup = BeautifulSoup(html, 'lxml')
blocks = soup.find_all('tr', class_='with-hover')
if len(blocks) > 0:
for block in blocks:
product_url = 'https://www.chipdip.ru' + block.find('td', class_='h_name').find('a',
class_='link').get(
'href')
product_avtor = block.find('div', class_='nw').find('span').text.strip()
product_path = f'{block_name}/{catalog_header}/{category_name}/{product_avtor}/'
get_data(product_url, product_path)
else:
break
def get_categories_urls(block_name, url):
html = get_html(url)
soup = BeautifulSoup(html, 'lxml')
items = soup.find_all('div', class_='catalog__g1 clear')
for item in items:
catalog_header = item.find('div', class_='catalog__header').find('a',
class_='link link_dark like-header like-header_3').text.strip()
catalog_items = item.find_all('li', class_='catalog__item')
for catalog_item in catalog_items:
category_url = 'https://www.chipdip.ru' + catalog_item.find('a', class_='link').get('href')
category_name = catalog_item.find('a', class_='link').text.strip()
get_block_url(block_name, catalog_header, category_name, category_url)
def get_content(html):
soup = BeautifulSoup(html, 'lxml')
blocks = soup.find('ul', class_='cat-menu').find_all('li')
for block in blocks:
block_url = 'https://www.chipdip.ru' + block.find('a').get('href')
block_name = block.find('a').text.strip()
get_categories_urls(block_name, block_url)
def main():
url = 'https://www.chipdip.ru'
get_content(get_html(url))
if __name__ == '__main__':
main()
Я тут что то намудрил с try/except, помогите разобраться.Проблемы начались в функции get_data(), когда начал искать description. На сайте сразу у третьего товара есть описание Вот этот товар, но оно почему то не выводится.(то же самое и с тех.параметрами)Я так понимаю ссылка на этот товар не попадает или что то еще, не понимаю, почему парсер работает так некорректно. Возможно это я придумал,но вроде когда была обвернута функция get_data() в try/except, а сам блок с поиском description нет, то тогда вроде выводилось описание...ну незнаю... На мой взгляд программа должна работать корректно,несколько раз просматривал алгоритм, но почему то ничего не нашел...пожалуйста помогите разобраться