Описание проблемы:
Я пытаюсь автоматизировать процесс, при котором я могу посетить веб-сайт, наведя указатель мыши на навигацию по меню. и нажмите на каждую опцию категории навигации в раскрывающемся списке уровня 1, посетите эту страницу, соберите подробную информацию о 20 лучших продуктах на этой странице и поместите ее в файл Excel. Если на этой странице нет какого-либо продукта, скрипт продолжит прокручиваться вниз, пока не достигнет конца страницы, и если элемент Product-div не найден, он вернется в начало страницы и щелкнет следующую категорию в списке. панель навигации
Определения функций:
< Функцияstrong>scroll_and_click_view_more предназначена для прокрутки страницы вниз, функция prod_vitals предназначена для сбора сведений о продукте, специфичных для каждой страницы, а функция prod_count предназначена для извлечения общего количества товары на каждой странице и создание сводки по всем страницам.
Описание ошибки:
< blockquote>
Поскольку веб-сайт создан на японском языке, я хочу перевести каждую страницу, когда я ее открываю, на английский язык, а затем выполнить очистку. Я написал функцию translate_page для перевода страницы и вызываю эту функцию каждый раз, когда открываю новую страницу из своей функции очистки. Код работает нормально, как и ожидалось, единственная проблема заключается в том, что я по-прежнему получаю все результаты на японском языке, а не на английском.
Я прикрепляю свой код ниже:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import pandas as pd
import time
import re
import os
import shutil
import datetime
import openpyxl
import chromedriver_autoinstaller
from openpyxl import Workbook
from openpyxl.styles import PatternFill
from openpyxl.utils.dataframe import dataframe_to_rows
#custom_path = r"c:\Users\DELL\Documents\Self_Project" # Define the custom path where you want ChromeDriver to be installed
#temp_path=chromedriver_autoinstaller.install() # Installs the ChromeDriver to a temporary directory and returns the path to that directory.
#print("Temporary path",temp_path)
#final_path = os.path.join(custom_path, "chromedriver.exe") # constructs and stores the full path to the ChromeDriver executable in the custom directory.
#shutil.move(temp_path, final_path) # Moves the ChromeDriver executable from the temporary directory to the custom directory.
#print("ChromeDriver installed at:", final_path)
date_time = datetime.datetime.now().strftime("%m%d%Y_%H%M%S")
file_name = f'CRTL_JP_staging_products_data_{date_time}.xlsx'
products_summary = []
max_count_of_products=20
def scroll_and_click_view_more(driver,href):
flag=False
last_height = driver.execute_script("return window.pageYOffset + window.innerHeight")
while True:
try:
driver.execute_script("window.scrollBy(0, 800);")
time.sleep(4)
new_height1 = driver.execute_script("return window.pageYOffset + window.innerHeight")
try:
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div.product-tile')))
except Exception as e:
new_height = driver.execute_script("return window.pageYOffset + window.innerHeight")
if new_height1 == last_height and flag==False:
print("Reached the end of the page and no product tiles were found: ",href)
return "No product tiles found"
else:
last_height = new_height
continue
div_count = 0
flag=True
response = driver.page_source
soup = BeautifulSoup(response, 'html.parser')
div_elements = soup.find_all('div', class_ = 'product-tile')
div_count = len(div_elements)
if(div_count > max_count_of_products):
return(driver.page_source)
driver.execute_script("window.scrollBy(0, 300);")
time.sleep(3)
new_height = driver.execute_script("return window.pageYOffset + window.innerHeight")
#print(new_height)
if new_height == last_height:
print("Reached the end of the page: ",href)
return("Reached the end of the page.")
break
else:
last_height = new_height
except Exception as e:
print(e)
break
def prod_vitals(soup,title,url):
count_of_items=1
products_data = [] # Array to store all product data for our excel sheet
for div in soup.find_all('div', class_ = 'product-tile'): # Iterate over each individual product-tile div tag
if count_of_items
Подробнее здесь: https://stackoverflow.com/questions/790 ... nium-autom