使用python+selenium,在访问百度贴吧帖子时,如果是直接进入对应贴吧网站,再定位元素点开帖子,没有问题。但是先在百度贴吧首页搜索贴吧,再定位元素点开帖子,元素无法定位到。使用的火狐浏览器
正常运行的代码:
br = webdriver.Firefox(service=Service(r'D:\seleniumJava\drivers\geckodriver.exe'))
br.get('https://tieba.baidu.com/f?ie=utf-8&kw=%E6%88%98%E8%88%B0%E4%B8%96%E7%95%8C&fr=search')
time.sleep(2)
element='/html/body/div[3]/div/div[2]/div/div/div[1]/div/div/div/div[5]/ul/li[2]/div/div[2]/div/div/a'
title=br.find_element(By.XPATH, element).text
print(title)
br.find_element(By.XPATH,element).click()
无法定位到元素的代码:
br = webdriver.Firefox(service=Service(r'D:\seleniumJava\drivers\geckodriver.exe'))
br.get('https://tieba.baidu.com/index.html')
time.sleep(3)
br.find_element(By.XPATH, '//*[@id="wd1"]').send_keys('战舰世界' + Keys.ENTER)
time.sleep(1)
element='/html/body/div[3]/div/div[2]/div/div/div[1]/div/div/div/div[5]/ul/li[2]/div/div[2]/div/div/a'
title=br.find_element(By.XPATH, element).text
print(title)
报错提示
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element:
/html/body/div[3]/div/div[2]/div/div/div[1]/div/div/div/div[5]/ul/li[2]/div/div[2]/div/div/a
我检查过,窗口句柄没有改变,是同一个窗口,也没有框架存在,而且用selenium IDE操作第二种的话,是能够正常搜索进入对应贴吧并打开第一个非置顶帖的
这个是按照你说的操作取出的xpath:
/html/body/div[3]/div/div[2]/div/div/div[1]/div/div/div/div[5]/ul/li[2]/div/div[2]/div[1]/div[1]/a
这个是报错脚本里的xpath:
/html/body/div[3]/div/div[2]/div/div/div[1]/div/div/div/div[5]/ul/li[2]/div/div[2]/div/div/a
确定写的xpath是对的?
会不会是在搜索出对应贴吧后,页面元素尚未加载完全,这时去定位是找不到的
所以在定位置顶帖子前加个等待试试?