如何从元素列表中提取数据 python

how to extract data from an element list python

我正在做一个真正阻碍了我的项目我经常在这里问问题,你帮了我很多,因为我还是个初学者,我的项目包括制作一个有竞争力的酒店价格表 table对于一个代理机构来说,我想让它自动化是一个痛苦的动作,我成功地提取了关税和它们的价格,但问题是我想让他只给我选定的房间 我为您提供了代码和输出我删除了我想在我的输出中删除的数据我还添加了图像以更好地澄清事情如果你们中的任何人可以帮助我提前谢谢你。

注意:感谢 pmadhu 的回答问题已解决,但现在它显示所有酒店的价格相同。

#!/usr/bin/env python
# coding: utf-8
import json
import time
from time import sleep
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.common.exceptions import StaleElementReferenceException

# create path and start webdriver
PATH = "C:\chromedriver.exe"
driver = webdriver.Chrome(PATH)

# first get website
driver.get('https://tn.tunisiebooking.com/')
wait = WebDriverWait(driver, 20)

# params to select
params = {
    'destination': 'Nabeul',
    'date_from': '24/08/2021',
    'date_to': '25/08/2021',
    'bedroom': '1'
}

# select destination
destination_select = Select(driver.find_element_by_id('ville_des'))
destination_select.select_by_value(params['destination'])

# select bedroom
bedroom_select = Select(driver.find_element_by_id('select_ch'))
bedroom_select.select_by_value(params['bedroom'])

# select dates
script = f"document.getElementById('depart').value ='{params['date_from']}';"
script += f"document.getElementById('checkin').value ='{params['date_to']}';"
driver.execute_script(script)

# submit form
btn_rechercher = driver.find_element_by_id('boutonr')
btn_rechercher.click()
sleep(10)

# ----------------------------------------------------------------------------
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import StaleElementReferenceException,NoSuchElementException
urls = []
hotels = driver.find_elements_by_xpath("//div[starts-with(@id,'produit_affair')]")
for hotel in hotels:
    link = hotel.find_element_by_xpath(".//span[@class='tittre_hotel']/a").get_attribute("href")
    urls.append(link)
for url in urls:
    driver.get(url)
    try:
        name = driver.find_element_by_xpath("//div[@class='bloc_titre_hotels']/h2").text
        arropt = driver.find_element_by_xpath("//div[contains(@class,'line_result')][1]")
        opt = arropt.find_element_by_tag_name("b").text
        num = len(arropt.find_elements_by_tag_name("option"))
        optiondata = {}
        achats = {}
        marges= {}
        selection = Select(driver.find_element_by_id("arrangement"))
        for i in range(num):
            try:
                selection = Select(driver.find_element_by_id("arrangement"))
                selection.select_by_index(i)
                time.sleep(2)
                arr = driver.find_element_by_xpath("//select[@id='arrangement']/option[@selected='selected']").text
                prize = driver.find_element_by_id("prix_total").text
                
                optiondata[arr]=prize

                
                btn_passe = driver.find_element_by_xpath('//*[@id="resultat"]/div/form/div/div[2]/div[1]/div[2]/div[2]/div/div ')
                btn_passe.click()
                sleep(2)
                                    # params to select
                params = {
                            'civilite_acheteur': 'Mlle',
                            'prenom_acheteur': 'test',
                            'nom_acheteur': 'test',
                            'e_mail_acheteur': 'test@gmail.com',
                            'portable_acheteur': '22222222'
                        }

                        # select civilite
                civilite_acheteur = Select(driver.find_element_by_id('civilite_acheteur'))
                civilite_acheteur.select_by_value(params['civilite_acheteur'])

                        # saisir prenom 
                script = f"document.getElementById('prenom_acheteur').value ='{params['prenom_acheteur']}';"
                script += f"document.getElementById('nom_acheteur').value ='{params['nom_acheteur']}';"
                script += f"document.getElementById('e_mail_acheteur').value ='{params['e_mail_acheteur']}';"
                script += f"document.getElementById('portable_acheteur').value ='{params['portable_acheteur']}';"
                driver.execute_script(script)

                        # submit form
                btn_rechercher = driver.find_element_by_id('titre_Hammamet')
                btn_rechercher.click()
                sleep(2)

                btn_rechercher = driver.find_element_by_id('boutonr')
                btn_rechercher.click()
                sleep(3)
                
                achat = driver.find_element_by_xpath('/html/body/header/div[2]/div[1]/div[1]/div[4]/div[2]/div[2]').text.replace(' TND', '')
                achats[arr]=achat

                marge =int(((float(prize) - float(achat)) / float(achat)) * 100);

                marges[arr]=marge
                optiondata[arr]=prize,achat,marge
                
                driver.get(url)
                btn_passe = driver.find_element_by_xpath('//*[@id="moteur_rech"]/form/div/div[3]/div')
                btn_passe.click()
                sleep(2)
                

            except StaleElementReferenceException:
                pass
            
       
    except NoSuchElementException:
        pass
    print("{} : {} - {}".format(name,opt,optiondata))
    

尝试下面的代码一次:

from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import StaleElementReferenceException,NoSuchElementException

hotels = driver.find_elements_by_xpath("//div[starts-with(@id,'produit_affair')]")
for hotel in hotels:
    link = hotel.find_element_by_xpath(".//span[@class='tittre_hotel']/a").get_attribute("href")
    urls.append(link)
for url in urls:
    driver.get(url)
    try:
        name = driver.find_element_by_xpath("//div[@class='bloc_titre_hotels']/h2").text
        arropt = driver.find_element_by_xpath("//div[contains(@class,'line_result')][1]")
        opt = arropt.find_element_by_tag_name("b").text
        num = len(arropt.find_elements_by_tag_name("option"))
        optiondata = {}
        selection = Select(driver.find_element_by_id("arrangement"))
        for i in range(num):
            try:
                selection = Select(driver.find_element_by_id("arrangement"))
                selection.select_by_index(i)
                time.sleep(2)
                arr = driver.find_element_by_xpath("//select[@id='arrangement']/option[@selected='selected']").text
                prize = driver.find_element_by_id("prix_total").text
                optiondata[arr]=prize
            except StaleElementReferenceException:
                pass
    except NoSuchElementException:
        pass
    print("{} : {} - {} - {}".format(name,opt,num,optiondata))

并且输出:

Tui Blue Scheherazade Sousse : Double Standard Vue Mer - 1 - {'Demi Pension': '114'}
Golf Residence GAS Sousse : Double--Standard - 2 - {'Demi Pension': '51', 'Petit Dejeuner': '42'}
Sindbad Center GAS Sousse : Chambre Double - 2 - {'Petit Dejeuner': '27', 'Logement seul': '22'}