Парсинг на Python + BeautifulSoup
Вот код
import requests
from bs4 import BeautifulSoup as BS
import csv
import time
def get_html(url):
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 OPR/76.0.4017.177'
}
html = requests.get(url, headers=headers).text
return html
def write_csv(data):
with open('wild_pars.csv', 'a') as f:
writer = csv.writer(f, delimiter=';')
writer.writerow((data['class'],
data['category'],
data['brand_name'],
data['good_name'],
data['price'],
data['url']))
def fix_brand_name(text):
name = text.split('/')[0].strip()
return name
def fix_price(text):
price = text.replace(' ', '').replace('₽', '')
return price
def pars_content(class__, category, small_url):
root = 'https://www.wildberries.ru'
for page in range(1, 5000):
pagination = f'?page={page}'
url = small_url + pagination
html = get_html(url)
time.sleep(2)
soup = BS(html, 'lxml')
contents = soup.find_all('div', class_='dtList-inner')
if len(contents) == 0:
break
else:
for content in contents:
try:
brand_name = content.find('strong', class_='brand-name c-text-sm').text.strip()
fbrand_name = fix_brand_name(brand_name)
except:
fbrand_name = 'Брэнд отсутствует'
try:
good_name = content.find('span', class_='goods-name c-text-sm').text.strip()
except:
good_name = 'Название отсутствует'
try:
price = content.find('span', class_='price').find('ins', class_='lower-price').text.strip()
fprice = fix_price(price)
except:
price = content.find('span', class_='lower-price').text.strip()
fprice = fix_price(price)
try:
href_content = root + content.find('a', class_='ref_goods_n_p j-open-full-product-card').get('href').strip()
except:
href_content = root + content.find('a', class_='ref_goods_n_p j-open-full-product-card is-adult').get(
'href').strip()
content_data = {'class': class__,
'category': category,
'brand_name': fbrand_name,
'good_name': good_name,
'price': fprice,
'url': href_content}
write_csv(content_data)
def main(url):
html = get_html(url)
soup = BS(html, 'lxml')
all_menu = soup.find('ul', class_='menu-burger__main-list').find_all(
class_='menu-burger__main-list-item j-menu-main-item')
all_menu_dict = {}
for i in all_menu:
name = i.find('a').text
href = i.find('a').get('href')
all_menu_dict[name] = href
for key in all_menu_dict:
try:
html = get_html(all_menu_dict[key])
soup = BS(html, 'lxml')
all_catalog = soup.find('ul', class_='maincatalog-list-2').find_all('a')
for i in all_catalog:
root = 'https://www.wildberries.ru'
category = i.text
href = root + i.get('href')
pars_content(key, category, href)
except:
pass
if __name__ == '__main__':
url = 'https://www.wildberries.ru'
main(url)
Написал парсер товаров с wildberries. По моему должен работать нормально,все проверял несколько раз,но он почему то все равно работает не корректно.Проблема такая,парсер собирает товары по категориям с магазина (пример: категория женщинам - одежда(спарсил),затем женщинам-большие размеры и т.д.).Но парсер почему то после категории женщинам-одежда парсить начинает уже следующую мужчинам-одежда. Т.е. большая часть товаров "женщинам " не парсится. Не понимаю почему так,ссылки проверял,поступают корректные, но парсер почему то перепрыгивает множество категорий...Помогите разобраться


