Article From:https://segmentfault.com/q/1010000015629318
Question:

Using Python+selenium+webdriver to do automated testing, it is found that no page elements can be crawled. My process is like this: open the Baidu home page, enter the segementfault click search, select the first search results, go to the home page after thinking whether or not,Whatever I do, none of the elements on the page are grabbed, prompting me to selenium. common. exceptions. NoSuchElementException: Message: Unable to locateElement:.

But it is very strange that if I go straight to the homepage of no, I can grab the elements of the page without Baidu search, and the code is the same, without any change.

The code is as follows:

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()

Answer 0:

Recommend printingraw_html To glance at

Answer 1:

You need to switch windows_handle. Otherwise, the focus of chromedriver is still Baidu’s tab, which does not locate the new tab page elements.
Baidu or Google keyword “selenium driver.current_window_handle”
Try it.

Answer 2:
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()

No problem testing – replace Chrome with Firefox

Leave a Reply

Your email address will not be published. Required fields are marked *