Вопрос простой. У меня есть эти продукты в списке, результат поиска. при нажатии на кнопку он переходит на новую вкладку. Мое намерение простое: нажать на этот продукт, сосредоточиться на этой новой вкладке, удалить нужную мне информацию, а затем закрыть новую вкладку и вернуться к предыдущей вкладке и так далее по циклу. Вот как я пытаюсь это сделать, но программа просто игнорирует это: ошибку не выдает, но делает не то, что я хочу, даже новую вкладку не открывает.
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException, TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import json
import logging
import requests
import pandas as pd
from bs4 import BeautifulSoup
from urllib.parse import urlparse
import re
from fpdf import FPDF
from selenium import webdriver
from urllib.parse import urlparse
import undetected_chromedriver as uc
from selenium import webdriver
precos = []
tamanhos = []
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
driver = uc.Chrome(options=options)
#options.add_argument(f"--proxy-server={proxy}")
#options.add_argument("start-maximized")
#options.add_argument("disable-infobars")options.add_argument("--disable-extensions")
actions = ActionChains(driver)
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--no-sandbox")
options.add_argument("--verbose")
#options.add_argument("--remote-debugging-port=9222")
options.add_argument('--headless')
options.add_argument("--disable-gpu")
data_planilha = []
precos_m2 = []
url_base = "https://www.vivareal.com.br/venda/ceara ... aucaia,,,/"
driver.get(url_base)
#driver.find_element(By.XPATH, "//ul[@class = 'header__nav-links']/li[2]/a").click()
#driver.implicitly_wait(30)
resultados = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//section[@class = 'results__main']" )))
quantidade_imoveis = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//strong[@class = 'results-summary__count js-total-records']"))).text
quantidade_imoveis = int(quantidade_imoveis)
print(quantidade_imoveis)
try:
botao_proximo = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//button[@title = 'Próxima página']")))
while True:
time.sleep(1)
imoveis = WebDriverWait(driver, 200).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class = 'results-list js-results-list']/div")))
print("entrou")
for index, value in enumerate(imoveis):
driver.implicitly_wait(20)
imoveis = WebDriverWait(driver, 200).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class = 'results-list js-results-list']/div")))
driver.execute_script("arguments[0].scrollIntoView(true);", imoveis[index])
time.sleep(3)
tamanho = imoveis[index].find_element(By.XPATH, ".//span[@class = 'property-card__detail-value js-property-card-value property-card__detail-area js-property-card-detail-area']").text
#driver.execute_script("arguments[0].scrollIntoView(true);", tamanho)
# tamanho = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, ".//span[@class = 'property-card__detail-value js-property-card-value property-card__detail-area js-property-card-detail-area']"))).text
print(tamanho)
driver.implicitly_wait(20)
preco = imoveis[index].find_element(By.XPATH, ".//div[@class = 'property-card__price js-property-card-prices js-property-card__price-small']/p").text
preco_imovel = "".join(re.findall('\d+', preco))
price = int(preco_imovel)
links = imoveis[index].find_elements(By.CLASS_NAME, "property-card__labels-container js-main-info js-listing-labels-link")
for link in links:
link.click()
driver.switch_to.window(driver.window_handles[1])
driver.execute_script('window.scrollBy(0, 500)')
anuncio_ano = WebDriverWait(driver, 100).until(EC.visibility_of_element_located((By.XPATH, "//div[@class = 'description__info-date big-space']/span[2]"))).text
driver.implicitly_wait(20)
driver.close()
driver.switch_to.window(driver.window_handles[0])
#preco = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, ".//div[@class = 'property-card__price js-property-card-prices js-property-card__price-small']/p"))).text
size = int(tamanho)
print(preco_imovel)
precos.append(int(price))
tamanhos.append(size)
preco_m2 = price/size
print(preco_m2)
precos_m2.append(preco_m2)
print(anuncio_ano)
if("2024" in anuncio_ano):
quantidade_2024 += 1
botao_proximo = driver.find_element(By.XPATH, "//button[@title = 'Próxima página']")
valor = botao_proximo.get_attribute("data-page")
if valor != "":
driver.execute_script('arguments[0].click()', botao_proximo)
else:
break
except NoSuchElementException:
print("última página")
tamanho_medio = sum(tamanhos)/quantidade_imoveis
preco_medio_total = sum(precos)/quantidade_imoveis
precos_m2_total = sum(precos_m2)/quantidade_imoveis
data_planilha.append({
'URL': url_base,
'Número de anúncios': quantidade_imoveis,
'Preço Médio': preco_medio_total,
'Tamanho Médio': tamanho_medio,
'Preço Médio por m2': precos_m2_total,
})
df_planilha = pd.DataFrame(data_planilha)
df_planilha.to_excel("catalogo_vivareal.xlsx")
print("salvou")
driver.quit()
Подробнее здесь: https://stackoverflow.com/questions/791 ... h-selenium
Как переключиться на новую вкладку и вернуться на предыдущую вкладку с помощью селена? ⇐ Python
Программы на Python
1732472300
Anonymous
Вопрос простой. У меня есть эти продукты в списке, результат поиска. при нажатии на кнопку он переходит на новую вкладку. Мое намерение простое: нажать на этот продукт, сосредоточиться на этой новой вкладке, удалить нужную мне информацию, а затем закрыть новую вкладку и вернуться к предыдущей вкладке и так далее по циклу. Вот как я пытаюсь это сделать, но программа просто игнорирует это: ошибку не выдает, но делает не то, что я хочу, даже новую вкладку не открывает.
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException, TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import json
import logging
import requests
import pandas as pd
from bs4 import BeautifulSoup
from urllib.parse import urlparse
import re
from fpdf import FPDF
from selenium import webdriver
from urllib.parse import urlparse
import undetected_chromedriver as uc
from selenium import webdriver
precos = []
tamanhos = []
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
driver = uc.Chrome(options=options)
#options.add_argument(f"--proxy-server={proxy}")
#options.add_argument("start-maximized")
#options.add_argument("disable-infobars")options.add_argument("--disable-extensions")
actions = ActionChains(driver)
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--no-sandbox")
options.add_argument("--verbose")
#options.add_argument("--remote-debugging-port=9222")
options.add_argument('--headless')
options.add_argument("--disable-gpu")
data_planilha = []
precos_m2 = []
url_base = "https://www.vivareal.com.br/venda/ceara/caucaia/bairros/caucaia/#onde=,Cear%C3%A1,Caucaia,Bairros,Caucaia,,,,BR%3ECeara%3ENULL%3ECaucaia%3EBarrios%3ECaucaia,,,/"
driver.get(url_base)
#driver.find_element(By.XPATH, "//ul[@class = 'header__nav-links']/li[2]/a").click()
#driver.implicitly_wait(30)
resultados = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//section[@class = 'results__main']" )))
quantidade_imoveis = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//strong[@class = 'results-summary__count js-total-records']"))).text
quantidade_imoveis = int(quantidade_imoveis)
print(quantidade_imoveis)
try:
botao_proximo = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//button[@title = 'Próxima página']")))
while True:
time.sleep(1)
imoveis = WebDriverWait(driver, 200).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class = 'results-list js-results-list']/div")))
print("entrou")
for index, value in enumerate(imoveis):
driver.implicitly_wait(20)
imoveis = WebDriverWait(driver, 200).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class = 'results-list js-results-list']/div")))
driver.execute_script("arguments[0].scrollIntoView(true);", imoveis[index])
time.sleep(3)
tamanho = imoveis[index].find_element(By.XPATH, ".//span[@class = 'property-card__detail-value js-property-card-value property-card__detail-area js-property-card-detail-area']").text
#driver.execute_script("arguments[0].scrollIntoView(true);", tamanho)
# tamanho = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, ".//span[@class = 'property-card__detail-value js-property-card-value property-card__detail-area js-property-card-detail-area']"))).text
print(tamanho)
driver.implicitly_wait(20)
preco = imoveis[index].find_element(By.XPATH, ".//div[@class = 'property-card__price js-property-card-prices js-property-card__price-small']/p").text
preco_imovel = "".join(re.findall('\d+', preco))
price = int(preco_imovel)
links = imoveis[index].find_elements(By.CLASS_NAME, "property-card__labels-container js-main-info js-listing-labels-link")
for link in links:
link.click()
driver.switch_to.window(driver.window_handles[1])
driver.execute_script('window.scrollBy(0, 500)')
anuncio_ano = WebDriverWait(driver, 100).until(EC.visibility_of_element_located((By.XPATH, "//div[@class = 'description__info-date big-space']/span[2]"))).text
driver.implicitly_wait(20)
driver.close()
driver.switch_to.window(driver.window_handles[0])
#preco = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, ".//div[@class = 'property-card__price js-property-card-prices js-property-card__price-small']/p"))).text
size = int(tamanho)
print(preco_imovel)
precos.append(int(price))
tamanhos.append(size)
preco_m2 = price/size
print(preco_m2)
precos_m2.append(preco_m2)
print(anuncio_ano)
if("2024" in anuncio_ano):
quantidade_2024 += 1
botao_proximo = driver.find_element(By.XPATH, "//button[@title = 'Próxima página']")
valor = botao_proximo.get_attribute("data-page")
if valor != "":
driver.execute_script('arguments[0].click()', botao_proximo)
else:
break
except NoSuchElementException:
print("última página")
tamanho_medio = sum(tamanhos)/quantidade_imoveis
preco_medio_total = sum(precos)/quantidade_imoveis
precos_m2_total = sum(precos_m2)/quantidade_imoveis
data_planilha.append({
'URL': url_base,
'Número de anúncios': quantidade_imoveis,
'Preço Médio': preco_medio_total,
'Tamanho Médio': tamanho_medio,
'Preço Médio por m2': precos_m2_total,
})
df_planilha = pd.DataFrame(data_planilha)
df_planilha.to_excel("catalogo_vivareal.xlsx")
print("salvou")
driver.quit()
Подробнее здесь: [url]https://stackoverflow.com/questions/79169511/how-switch-to-new-to-tab-and-go-back-to-the-previous-tab-with-selenium[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия