我要自动搜索斯图加特(德国)附近的五星级酒店。然后用selenium框架编写了一个python脚本。我也找过类似的问题,但都没找到。
下面是我的浏览器驱动程序代码在一个单独的文件(browserDriver.py):
#-*-coding:utf-8-*-
import os
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--incognito')
chromedriver = r"UserssimonDocumentschromedriver_win32chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
和searchAutomattecally_hotelstars_eu.py -文件:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import browserDriver as bd
import time
val_land = 'Germany'
val_city = 'Stuttgart'
val_radius = '100'
val_stars = '5'
bd.driver.get('https://www.hotelstars.eu/de/deutschland/service/hotelsuche/')
bd.driver.implicitly_wait(10)
# accept Cookies
bd.driver.find_element(By.ID, '564').click()
print('- - - Status: Cookies accepted')
element_land =bd.driver.find_element(By.NAME, 'country')
print(element_land.text)
all_options = element_land.find_elements(By.TAG_NAME, 'option')
for option in all_options:
if option == val_land:
select_land = Select(option)
print('- - - Status: Geeeeeeeeeht')
print('- - - Status: if-Bedingung beendet')
select_land.select(By.Value, val_land)
print('- - - Status: ', select_land)
element_stadt = bd.driver.find_element(By.ID, 'city')
element_stadt.send_keys(val_city)
element_radius = bd.driver.find_element(By.ID, 'radius')
select_radius = Select(bd.driver.find_element_by_name('radius'))
select_radius.select_by_value(val_radius)
element_stars = bd.driver.find_element(By.ID, 'stars')
select_stars = Select(bd.driver.find_element(By.NAME, 'stars'))
select_stars.select_by_value(val_stars)
bd.driver.find_element_by_id("sendbtn").click()
网站hotelstars.eu链接
下面是错误信息:
Traceback (most recent call last):
File "...searchAutomatecally_hotelstars_eu.py", line 28, in <module>
element_land =bd.driver.find_element(By.NAME, 'country')
File "...libsite-packagesseleniumwebdriverremotewebdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "...libsite-packagesseleniumwebdriverremotewebdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "...libsite-packagesseleniumwebdriverremoteerrorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="country"]"}
(Session info: chrome=93.0.4577.63)
有人能帮忙吗??
因为所需的元素在这个iframe中:
<iframe id="searchIframe" scrolling="no" src="/fileadmin/bsdist/theme/modules/hotelstars_search/?L=1" width="100%" height="200px" frameborder="0" style="border: 0px; height: 250px;" allowfullscreen=""></iframe>
所以你必须先切换到这个iframe,然后你可以与所需的元素交互
bd.switch_to.frame(bd.find_element_by_xpath("//iframe[@id='searchIframe']"))
,然后像这样与国家进行交互:-
element_land = bd.driver.find_element(By.NAME, 'country')