[英]How to find hidden class with Selenium
我目前正在使用 Python 進行演示 Selenium 項目。 我已經能夠導航到一個頁面,但是當嘗試在“div 類”中收集文本時,selenium 無法找到 HTML:要收集的代碼
我已經使用了等待功能,但代碼仍然找不到 Html 元素。
任何有關如何解決此問題的建議將不勝感激,請參閱下面的代碼:我的 selenium 的圖像
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
import json
# establish Json dict
global data
data = {}
global date
date = '''&checkin=2021-02-22&checkout=2021-02-28&adults=1&source'''
def find_info(place):
data[place] = []
driver = webdriver.Chrome('chromedriver.exe')
driver.get("https://www.airbnb.co.uk/")
time.sleep(2)
#first_page_search_bar
search_bar = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "_1xq16jy")))
time.sleep(2)
search_bar.clear()
time.sleep(2)
search_bar.send_keys(f"{place}")
time.sleep(2)
enter_button = driver.find_element_by_class_name("_1mzhry13")
enter_button.click()
#load page
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "_ljad0a")))
page = driver.current_url
new_url = page.replace("&source", date)
# driver = webdriver.Chrome('chromedriver.exe')
driver.get(new_url)
time.sleep(3)
click_button = driver.find_element_by_xpath('//*[@id="menuItemButton-price_range"]/button')
click_button.click()
time.sleep(5)
price = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, '/html/body/div[16]/section/div/div/div[2]/div/section/div[2]/div/div/div[1]')))
print(price)
find_info("London, United Kingdom")
我已經在腳本末尾修復了xpath
:
price = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, '(//div[@role="menu"]//div[@dir="ltr"])[1]/preceding-sibling::div')))
print(price.text)
說明:在<div role="menu"...
下有 3 個<div dir="ltr">
元素,第一個恰好在您要查找的 div 之后。 所以我們發現一個和 select 是前面的兄弟。
另一個建議:如果您在開始時查找輸入字段時將EC.element_to_be_clickable
EC.presence_of_element_located
則可以擺脫一些time.sleep
語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.