简体   繁体   English

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

[英]xpath returns more than one result, how to handle in python

I have started selenium using python.我已经使用 python 启动了 selenium。 I am able to change the message text using find_element_by_id.我可以使用 find_element_by_id 更改消息文本。 I want to do the same with find_element_by_xpath which is not successful as the xpath has two instances.我想对 find_element_by_xpath 做同样的事情,因为 xpath 有两个实例,所以不成功。 want to try this out to learn about xpath.想试试这个来了解 xpath。

I want to do web scraping of a page using python in which I need clarity on using Xpath mainly needed for going to next page.我想使用 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()

To elaborate on my comment you would use a list like this:为了详细说明我的评论,您可以使用这样的列表:

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)

The only real difference between find_elements_by_xpath and find_element_by_xpath is the first option returns a list that needs to be indexed. find_elements_by_xpathfind_element_by_xpath之间唯一真正的区别是第一个选项返回需要索引的列表。 Once it's indexed, it works the same as if you had run the second option!一旦它被编入索引,它的工作原理就好像你运行了第二个选项一样!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM