xpath返回多个结果,如何在python中处理

时间:2019-04-16 17:58:02

标签: python selenium-webdriver xpath

我已经使用python启动了硒。我可以使用find_element_by_id更改消息文本。我想对find_element_by_xpath进行相同的操作,因为xpath有两个实例,所以它不成功。想尝试一下以了解xpath。

我想使用python进行网页的网页抓取,在其中我需要明确使用Xpath,这主要是进入下一页的必要条件。

#This code works:
import time
import requests
import requests
from selenium import webdriver
driver = webdriver.Chrome()
url = "http://www.seleniumeasy.com/test/basic-first-form-demo.html"
driver.get(url)
eleUserMessage = driver.find_element_by_id("user-message")
eleUserMessage.clear()
eleUserMessage.send_keys("Testing Python")
time.sleep(2)
driver.close()
#This works fine. I wish to do the same with xpath. 
#I inspect the the Input box in chrome, copy the xpath '//*[@id="user-message"]' which seems to refer to the other box as well.
# I wish to use xpath method to write text in this box as follows which does not work.

driver = webdriver.Chrome()
url = "http://www.seleniumeasy.com/test/basic-first-form-demo.html"
driver.get(url)
eleUserMessage = driver.find_elements_by_xpath('//*[@id="user-message"]')
eleUserMessage.clear()
eleUserMessage.send_keys("Test Python")
time.sleep(2)
driver.close()

1 个答案:

答案 0 :(得分:1)

要详细说明我的评论,请使用以下列表:

eleUserMessage_list = driver.find_elements_by_xpath('//*[@id="user-message"]')
my_desired_element = eleUserMessage_list[0] # or maybe [1]
my_desired_element.clear()
my_desired_element.send_keys("Test Python")
time.sleep(2)

find_elements_by_xpathfind_element_by_xpath之间唯一真正的区别是第一个选项返回需要索引的列表。一旦将其编入索引,其工作方式就如同您运行第二个选项一样!