鍍金池/ 問答/Python  HTML/ python+selenium+webdriver定位不到頁面元素,新人求幫忙,

python+selenium+webdriver定位不到頁面元素,新人求幫忙,困擾幾天了

使用Python+selenium+webdriver做自動化測試,發(fā)現(xiàn)抓取不到頁面元素。我的流程是這樣的:打開百度首頁,輸入segementfault點擊搜索,選擇第一個搜索結果,進入思否首頁之后,不管我怎么做,頁面上的所有元素都抓取不到,提示我selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: 。

但是很奇怪的是,我如果直接進入思否的首頁,不通過百度搜索,就可以抓取到頁面的元素,代碼都是一樣的,沒做任何改變。

代碼如下:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = webdriver.Firefox()
driver.get("https://www.baidu.com/")
print(driver.title)
driver.find_element_by_xpath('//*[@id="kw"]').send_keys('segmentfault')
driver.find_element_by_xpath('//*[@id="su"]').click()
time.sleep(3)
driver.find_element_by_xpath("/html/body/div[1]/div[5]/div[1]/div[3]/div[1]/h3/a").click()
time.sleep(5)
driver.find_element_by_xpath('/html/body/div[4]/div/div/div[1]/div[2]/a[1]').click()
driver.find_element_by_xpath('/html/body/div[4]/div/div/div[2]/div[4]/div[1]/div/a[2]/div[1]/h4').click()

回答
編輯回答
孤毒

建議打印 raw_html 看一下

2018年1月5日 15:37
編輯回答
蟲児飛

需要切換 windows_handle。否則 chromedriver 的焦點還在百度那個 tab,定位不到 新 tab 頁元素的。
百度或者谷歌關鍵字 “selenium driver.current_window_handle”
試試看吧

2018年1月12日 13:52
編輯回答
柒喵
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
print(driver.title)
driver.find_element_by_xpath('//*[@id="kw"]').send_keys('segmentfault')
driver.find_element_by_xpath('//*[@id="su"]').click()
time.sleep(3)
driver.find_element_by_xpath("/html/body/div[1]/div[5]/div[1]/div[3]/div[1]/h3/a").click()
time.sleep(5)

driver.switch_to_window(driver.window_handles[-1])

driver.find_element_by_xpath('/html/body/div[4]/div/div/div[1]/div[2]/a[1]').click()
driver.find_element_by_xpath('/html/body/div[4]/div/div/div[2]/div[4]/div[1]/div/a[2]/div[1]/h4').click()

已測試沒問題 - - 自行替換 Chrome 為 Firefox

2017年6月23日 12:39