无法使用selenium(python)找到元素

因此,我尝试查看网站中的 iframe,但无法弄清楚该元素属于何处。我试图通过类名访问元素。下面是我的代码,这是网站。


from requests import get

from bs4 import BeautifulSoup

from selenium.webdriver import Chrome

from selenium.webdriver.chrome.options import Options

from selenium import webdriver


browser = webdriver.Chrome(executable_path= '/Users/abeelcf/Downloads/chromedriver')

browser.get('https://www.redfin.com')

zipcode = input("Enter a zip code to look up: ")

search_form = browser.find_element_by_id('search-box-input')

search_form.send_keys(zipcode)

search_form.submit()


#pg 2

browser.find_element_by_id("MapHomeCard_0")

网址是https://www.redfin.com/zipcode/20007


问题出在最后一行。它找不到元素 MapHomeCard_0 ,说该元素没有这样的元素。


动漫人物
浏览 128回答 2
2回答

梵蒂冈之花

在 search_box 提交后,您需要使用网络驱动程序等待等待页面加载。WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'MapHomeCard_0')))还导入以下内容from selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC

ITMISS

要定位您需要引发WebDriverWait 的元素visibility_of_element_located(),您可以使用以下任一定位器策略:使用XPATH:driver.get('https://www.redfin.com')search_form = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='search-input-box' and @id='search-box-input'][@title='City, Address, School, Agent, ZIP']")))search_form.send_keys("20007")search_form.submit()print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='homecards']/div[@id='MapHomeCard_0']"))).text)使用CSS_SELECTOR:print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.homecards>div#MapHomeCard_0"))).text)控制台输出:LISTED BY REDFIN3D WALKTHROUGH$464,0001 Bed1 Bath1,014 Sq. Ft.2500 Q St NW #412, Washington, DC 20007注意:您必须添加以下导入:from selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as EC
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python