Пасринг сайта Python
Есть проблема. Я парсю эту страницу: https://www.cian.ru/cat.php?deal_type=sale&engine_version=2&object_type%5B0%5D=1&offer_type=flat&p=54®ion=1
Далее перехожу на каждое объявление и получаю: название, цену, вид из окон, тип жилья.
У меня получаются списки из названий, цен и т.д.
И проблема в том, что поля "Вид из окон" на страницы объявления может и не быть. Из-за этого возникает ошибка: IndexError: list index out of range
name_list = ['name_1', 'name_2', 'name_3', 'name_4']
price_list = [123, 355, 56, 7]
window_view = ["во двор", 'на улицу и двор']
И вот вопрос: Как мне проверить есть ли поле "Вид из окон" и если нет то в список добавить "none" на выходе я получаю json:
[
{
"title": "home_1",
"price": "123",
"window_view": "на улицу",
},
{
"title": "home_2",
"price": "355",
"window_view": "На улицу и двор",
},
{
"title": "home_3",
"price": "56",
"window_view": "На двор",
},
{
"title": "home_4",
"price": "7",
"window_view": "none"
}
]
и тут при создании словаря с дальнейшей записью в json возникает ошибка: IndexError: list index out of range
for i in range(0, len(title_result)):
to_json = {
"title": title_result[i],
"price": price_result[i],
"window_view": window_result[i]
}
если нужно вот полный код:
import requests
from bs4 import BeautifulSoup as BS
import json
url = "https://www.cian.ru/cat.php?deal_type=sale&engine_version=2&object_type%5B0%5D=1&offer_type=flat&p=54®ion=1"
headers = {"user-agent": "тут user-agent"}
r = requests.get(url, headers = headers)
soup = BS(r.content.decode("utf-8"), "html.parser")
url = soup.findAll("a", class_ = "c6e8ba5398--header--1fV2A")
url = [i.get('href') for i in url]
result = []
title_result = []
price_result = []
window_result = []
home_result = []
for i in url:
r = requests.get(i, headers = headers)
soup = BS(r.content.decode("utf-8"), "html.parser")
block = soup.find("div", class_ = "a10a3f92e9--section_divider--1zGrv")
block_li = block.findAll("li", class_ = "a10a3f92e9--item--_ipjK")
for i in block_li:
type_home = i.find("span", class_ = "a10a3f92e9--name--3bt8k").text
if type_home == "Тип жилья":
type_home = i.find("span", class_ = "a10a3f92e9--value--3Ftu5").text
home_result.append(type_home)
if type_home == "Вид из окон":
type_home = i.find("span", class_ = "a10a3f92e9--value--3Ftu5").text
window_result.append(type_home)
title = soup.find("h1", class_ = "a10a3f92e9--title--2Widg").text
price = soup.find("span", itemprop = "price").text
window_view = block.find("li", class_ = "a10a3f92e9--item--_ipjK").find("span", class_ = "a10a3f92e9--value--3Ftu5")
title_result.append(title)
price_result.append(price)
for i in range(0, len(title_result)):
to_json = {
"title": title_result[i],
"price": price_result[i],
"window_view": window_result[i],
}
result.append(to_json)
with open("test.json", "w", encoding = "utf-8") as file:
json.dump(result, file, indent = 2, ensure_ascii = False)
Заранее спасибо