поэтому я пытаюсь выполнить парсинг с помощью 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
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение