Парсинг Python. Как выполнить пагинацию и сохранить результат?
Продолжаю изучать парсинг. В качестве подопытного сайта выбрал вот такой интернет магазин: Сайт для обучения
Решил делать этот и последующие в 2 этапа:
- Селеном проходить все преграды, если такие возникнут и получать html файл.
- Парсить html с помощью bs и requests.
Selen в данном случае прост, как двери:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
driver = webdriver.Chrome(options=options, executable_path=r"D:\Python_lern\Project_new_oboi \chromedriver.exe")
url = 'https://oboi.ua/wallpaper/'
driver.get(url)
page = driver.page_source
with open('page.html', 'w', encoding='utf-8') as file:
file.write(page)
file.close()
driver.close()
driver.quit()
Получил ХТМЛ файл.И дальше получаю данные:
import requests
from bs4 import BeautifulSoup
import lxml
import csv
#Получаем ссылки на модели
# host = 'https://oboi.ua'
#
# all_links = []
#
# with open('page.html', 'r', encoding='utf-8') as f:
# contents = f.read()
# for i in range(0, 1):
# r = requests.get(url)
# soup = BeautifulSoup(contents, 'lxml')
#
# boxes = soup.find_all('div', class_='col-xs-6 col-sm-6 col-md-4 col-lg-3 c compare-del-parent')
# for i in boxes:
# links = host + i.find('a', class_='u').get('href')
# all_links.append(links)
#
# with open('all_links.txt', 'a') as f:
# for line in all_links:
# f.write(f'{line}\n')
#Парсим данные внутри карточки
with open('all_links.txt') as f:
lines = [line.strip() for line in f.readlines()]
data = []
for line in lines:
q = requests.get(line)
res = q.content
soup = BeautifulSoup(res, 'lxml')
model = soup.find('div', class_='view-products').find('h1').text
brand = soup.find('td', class_='col-xs-8').text
country = soup.find('td', class_='col-xs-8').find('b').find_next('b').text
article = soup.find(id='thiscode').text
size = soup.find\
(class_='table table-striped table-bord-bottom table-condensed').find_all('td') [8].find_next().text
type = soup.find\
(class_='table table-striped table-bord-bottom table-condensed').find_all('td')[10].find_next().text
price = soup.find('span', class_='order-table-cost').text
img = soup.find\
('div', class_='col-sm-3 col-md-5 col-lg-6').find(class_='img-responsive img-thumbnail').get('src')
data.append(
{
'model':model,
'brand':brand,
'country':country,
'article':article,
'size':size,
'type':type,
'price':price,
'img':img
}
)
#На этом этапе должен записываться файл
with open('all_models.csv', 'w', encoding='utf-8') as file:
writer = csv.writer(file, delimiter=';')
writer.writerow(['Model', 'Brand', 'Country', 'Article', 'Size', 'Type', 'Price', 'Img'])
for line in lines:
writer.writerow([soup['model'], soup['brand'], soup['country'], soup['article'], soup['size'], soup['type'], soup['price'], soup['img']])
вот на этом этапе возникает затруднение в сохранении всех данных в csv. В таком виде код создает файл только с заголовками. и с ошибкой "KeyError: 'model'".
Возникает 2 вопроса:
- как корректно записать файл ?
- как пройти пагинацию на данном сайте ? Желательно реализовать в блоке Селена. Но в данном случае не получается ни Селеном ни bs-ом. Xpath, CSS разные на кнопке "Далее" постоянно. По ID тоже не получается. В цикле так же не выходит, так как url всех страниц одинаковый.