поэтому я пытаюсь выполнить парсинг с помощью BeautifulSoup и нумерацию страниц с помощью Selenium, так как мне нужно что-то более быстрое, чем Selenium для парсинга. Таким образом, для каждого продукта он получит href этого продукта, объединится с базовым URL-адресом, а затем «перейдет» к этому документу (при реальной навигации открывается новая вкладка). Каждый раз, когда он получает сообщение «AttributeError: объект 'NoneType' не имеет атрибута 'text'» в
строке:
ad_year = sp.find("div", class_="description__info) -date big-space").text
soup.prettify() дает мне другой источник, который я вижу, когда набираю cntrl + U в своем браузере. Я пробовал как с помощью request.get, так и без него, результат всегда неверный, более того, ни в одном из них я не получаю правильный источник страницы.
вот код:
#imports
quantity_2024 = 0
quantity_2023 = 0
quantity_2022 = 0
quantity_2021 = 0
prices = []
sizes = []
spreadsheet_data = []
prices_per_m2 = []
spreadsheet_data = []
prices_per_m2 = []
# selenium configuration
line_url = "https://www.vivareal.com.br/venda/sp/ja ... &quartos=2"
base_url = "https://www.vivareal.com.br"
start_time = time.time()
driver.get(line_url)
product_page = ""
try:
next_button = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//button[@title = 'Next page']")))
while True:
current_page = driver.page_source
soup = BeautifulSoup(current_page, "lxml")
properties_container = soup.find("div", class_="results-list js-results-list")
properties = properties_container.find_all("div")
if not properties:
print("No properties found. Finishing.")
break # Exit the loop if no properties are found on the page
for property in properties:
size = property.find("span", class_="property-card__detail-value").text
size = int(re.sub(r"\D", "", size)) # Numbers only
print(size)
sizes.append(size)
# Get price
price = property.find("div", class_="property-card__price").text
price = int("".join(re.findall(r"\d+", price))) # Numbers only
print(price)
prices.append(price)
# Calculate price per m²
price_per_m2 = price / size if size else 0
print(price_per_m2)
prices_per_m2.append(price_per_m2)
links = property.find_all("a", class_="property-card__content-link js-card-title")
for link in links:
product_page = base_url + link["href"]
response = requests.get(product_page)
sp = BeautifulSoup(response.text, "lxml")
print(sp.prettify())
ad_year = sp.find("div", class_="description__info-date big-space").text
if "2024" in ad_year:
quantity_2024 += 1
elif "2023" in ad_year:
quantity_2023 += 1
elif "2022" in ad_year:
quantity_2022 += 1
elif "2021" in ad_year:
quantity_2021 += 1
# Check if there is a next page (if not, stop)
next_button = driver.find_element(By.XPATH, "//button[@title = 'Next page']")
value = next_button.get_attribute("data-page")
if value != "":
driver.execute_script('arguments[0].click()', next_button)
else:
break
except NoSuchElementException:
print("last page")
# Calculate averages
total_properties = len(prices)
average_size = sum(sizes) / total_properties if total_properties else 0
average_total_price = sum(prices) / total_properties if total_properties else 0
average_prices_per_m2 = sum(prices_per_m2) / total_properties if total_properties else 0
# Save data to spreadsheet
spreadsheet_data.append({
'URL': base_url,
'Number of ads': total_properties,
'Average Price': average_total_price,
'Average Size': average_size,
'Average Price per m2': average_prices_per_m2,
'Ads from 2024': quantity_2024,
'Ads from 2023': quantity_2023,
'Ads from 2022': quantity_2022,
'Ads from 2021': quantity_2021
})
df_spreadsheet = pd.DataFrame(spreadsheet_data)
df_spreadsheet.to_excel("catalog_vivareal.xlsx", index=False)
print("Spreadsheet saved successfully!")
print("--- %s seconds ---" % (time.time() - start_time))
`````
Подробнее здесь: https://stackoverflow.com/questions/791 ... r-nonetype
BeautifulSoup не находит элемент после «перенаправления». AttributeError: объект «NoneType» не имеет атрибута «текст». ⇐ Python
Программы на Python
1731783673
Anonymous
поэтому я пытаюсь выполнить парсинг с помощью BeautifulSoup и нумерацию страниц с помощью Selenium, так как мне нужно что-то более быстрое, чем Selenium для парсинга. Таким образом, для каждого продукта он получит href этого продукта, объединится с базовым URL-адресом, а затем «перейдет» к этому документу (при реальной навигации открывается новая вкладка). Каждый раз, когда он получает сообщение «AttributeError: объект 'NoneType' не имеет атрибута 'text'» в
строке:
ad_year = sp.find("div", class_="description__info) -date big-space").text
soup.prettify() дает мне другой источник, который я вижу, когда набираю cntrl + U в своем браузере. Я пробовал как с помощью request.get, так и без него, результат всегда неверный, более того, ни в одном из них я не получаю правильный источник страницы.
вот код:
#imports
quantity_2024 = 0
quantity_2023 = 0
quantity_2022 = 0
quantity_2021 = 0
prices = []
sizes = []
spreadsheet_data = []
prices_per_m2 = []
spreadsheet_data = []
prices_per_m2 = []
# selenium configuration
line_url = "https://www.vivareal.com.br/venda/sp/jacarei/bairros/loteamento-villa-branca/avenida-das-letras/#onde=,S%C3%A3o%20Paulo,Jacare%C3%AD,Bairros,Loteamento%20Villa%20Branca,Avenida%20das%20Letras,,,BR%3ESao%20Paulo%3ENULL%3EJacarei%3EBarrios%3ELoteamento%20Villa%20Branca,,,&quartos=2"
base_url = "https://www.vivareal.com.br"
start_time = time.time()
driver.get(line_url)
product_page = ""
try:
next_button = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//button[@title = 'Next page']")))
while True:
current_page = driver.page_source
soup = BeautifulSoup(current_page, "lxml")
properties_container = soup.find("div", class_="results-list js-results-list")
properties = properties_container.find_all("div")
if not properties:
print("No properties found. Finishing.")
break # Exit the loop if no properties are found on the page
for property in properties:
size = property.find("span", class_="property-card__detail-value").text
size = int(re.sub(r"\D", "", size)) # Numbers only
print(size)
sizes.append(size)
# Get price
price = property.find("div", class_="property-card__price").text
price = int("".join(re.findall(r"\d+", price))) # Numbers only
print(price)
prices.append(price)
# Calculate price per m²
price_per_m2 = price / size if size else 0
print(price_per_m2)
prices_per_m2.append(price_per_m2)
links = property.find_all("a", class_="property-card__content-link js-card-title")
for link in links:
product_page = base_url + link["href"]
response = requests.get(product_page)
sp = BeautifulSoup(response.text, "lxml")
print(sp.prettify())
ad_year = sp.find("div", class_="description__info-date big-space").text
if "2024" in ad_year:
quantity_2024 += 1
elif "2023" in ad_year:
quantity_2023 += 1
elif "2022" in ad_year:
quantity_2022 += 1
elif "2021" in ad_year:
quantity_2021 += 1
# Check if there is a next page (if not, stop)
next_button = driver.find_element(By.XPATH, "//button[@title = 'Next page']")
value = next_button.get_attribute("data-page")
if value != "":
driver.execute_script('arguments[0].click()', next_button)
else:
break
except NoSuchElementException:
print("last page")
# Calculate averages
total_properties = len(prices)
average_size = sum(sizes) / total_properties if total_properties else 0
average_total_price = sum(prices) / total_properties if total_properties else 0
average_prices_per_m2 = sum(prices_per_m2) / total_properties if total_properties else 0
# Save data to spreadsheet
spreadsheet_data.append({
'URL': base_url,
'Number of ads': total_properties,
'Average Price': average_total_price,
'Average Size': average_size,
'Average Price per m2': average_prices_per_m2,
'Ads from 2024': quantity_2024,
'Ads from 2023': quantity_2023,
'Ads from 2022': quantity_2022,
'Ads from 2021': quantity_2021
})
df_spreadsheet = pd.DataFrame(spreadsheet_data)
df_spreadsheet.to_excel("catalog_vivareal.xlsx", index=False)
print("Spreadsheet saved successfully!")
print("--- %s seconds ---" % (time.time() - start_time))
`````
Подробнее здесь: [url]https://stackoverflow.com/questions/79195846/beautifulsoup-not-finding-element-after-a-redirect-attributeerror-nonetype[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия