嗨在開始之前感謝您的幫助所以我正在嘗試抓取谷歌航班網站:
代碼是
from time import sleep
from selenium import webdriver
chromedriver_path = 'E:/chromedriver.exe'
def search(urrl):
driver = webdriver.Chrome(executable_path=chromedriver_path)
driver.get(urrl)
asd= "//div[@aria-label='Enter your destination']//div//input[@aria-label='Where else?']"
driver.find_element_by_xpath("/html/body/c-wiz[2]/div/div[2]/c-wiz/div/c-wiz/c-wiz/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[4]/div/div/div[1]/div/div/input").click()
sleep(2)
TextBox = driver.find_element_by_xpath(asd)
sleep(2)
TextBox.click()
sleep(2)
print(str(TextBox))
TextBox.send_keys('Karachi')
sleep(2)
search_button = driver.find_element_by_xpath('//*[@id="yDmH0d"]/c-wiz[2]/div/div[2]/c-wiz/div/c-wiz/c-wiz/div[2]/div[1]/div[1]/div[2]/div/button/div[1]')
sleep(2)
search_button.click()
print(str(search_button))
sleep(15)
print("DONE")
driver.close()
def main():
url = "https://www.google.com/travel/flights"
print(" Getitng Data ")
search(url)
if __name__ == "__main__":
main()
我已經通過使用開發工具復制 Xpath 完成了再次感謝
uj5u.com熱心網友回復:
您面臨的問題是,在文本框中輸入城市后,按鈕Karachi上方會顯示一個建議下拉選單。Search這就是例外的原因,因為下拉選單會收到點擊而不是搜索按鈕。該網站的預期用途是從下拉串列中選擇城市,然后繼續。
一個快速的解決方法是首先查找源中的所有下拉串列(有幾個),然后查找當前使用is_displayed(). 接下來,您將在建議的下拉串列中選擇第一個元素:
.....
TextBox.send_keys('Karachi')
sleep(2)
# the attribute(role) in the dropdowns element are named 'listbox'. Warning: This could change in the future
all_dropdowns = driver.find_elements_by_css_selector('ul[role="listbox"]')
# the active dropdown
active_dropdown = [i for i in all_dropdowns if i.is_displayed()][0]
# click the first suggestion in the dropdown (Note: this is very specific to your search. It could not be desirable in other circumstances and the logic can be modified accordingly)
active_dropdown.find_element_by_tag_name('li').click()
# I recommend using the advise @cruisepandey has offered above regarding usage of relative path instead of absolute xpath
search_button = driver.find_element_by_xpath("//button[contains(.,'Search')]")
sleep(2)
search_button.click()
.....
還建議領導@cruisepandey 提供的建議,包括更多關于硒中的顯式等待的研究,以撰寫性能更好的硒程式。一切順利
uj5u.com熱心網友回復:
而不是這個絕對的 xapth
//*[@id="yDmH0d"]/c-wiz[2]/div/div[2]/c-wiz/div/c-wiz/c-wiz/div[2]/div[1]/div[1]/div[2]/div/button/div[1]
我建議你有一個相對路徑:
//button[contains(.,'Search')]
另外,我建議您在嘗試單擊操作時進行顯式等待。
代碼:
search_button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(.,'Search')]")))
search_button.click()
您還需要以下匯入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
專家提示:
以全屏模式啟動瀏覽器。
driver.maximize_window()
您應該在命令之前有上述行driver.get(urrl)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/436002.html
標籤:Python 硒 硒网络驱动程序 网页抓取 硒铬驱动程序
