Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Selenium和Python定位元素并提取所需文本_Python_Python 3.x_Selenium_Xpath_Css Selectors - Fatal编程技术网

如何使用Selenium和Python定位元素并提取所需文本

如何使用Selenium和Python定位元素并提取所需文本,python,python-3.x,selenium,xpath,css-selectors,Python,Python 3.x,Selenium,Xpath,Css Selectors,我正在使用Selenium在网页上输入数据,但其中一个输入字段出现了问题。这是给我带来困难的HTML代码: <div class="form-group"> <label for="address">Enter your address</label> <input type="text" name="address" class="form-control" value="" style="font-size:1.8em;padding:15px;he

我正在使用Selenium在网页上输入数据,但其中一个输入字段出现了问题。这是给我带来困难的HTML代码:

<div class="form-group">
<label for="address">Enter your address</label>
<input type="text" name="address" class="form-control" value="" style="font-size:1.8em;padding:15px;height:40px">
<label for="address">Enter this code: 2784873 </label>
<input type="text" name="code" class="form-control" value="" style="font-size:1.8em;padding:15px;height:40px">
但是
codes
中返回的值是:

<selenium.webdriver.remote.webelement.WebElement (session="ae4e91d8ec7e2bc161", element="0.570523580858733-2")
您可以使用

driver.find_element_by_css_selector('.form-control + [for=address]').text
使用
replace()
删除
输入此代码:
字符串(如果需要)


这是一个类选择器“.”,相邻的兄弟组合符连接到属性=值选择器。所以属性为
的元素具有值地址,该值与类为表单控件的元素相邻

多亏了上面提供的线索,我才能够理解这一点。问到
codes.getText()
显示了什么,但是
getText()
是针对Selenium的Java版本的。在本例中,我使用的是Python,因此它应该是
。text

codes = driver.find_elements(By.XPATH, "//*[@id=\"page-wrapper\"]/div[2]/div[2]/center/form/div/label[2]").text
对于上面的示例,返回“输入此代码:2784873”

问题解决了,谢谢


编辑:同样感谢我编写此文件时,谁的解决方案也进来。

什么是
code.getText()
?不确定您要在哪里使用此解决方案。如果我执行
print(code.getText()
操作,我会收到一个错误:“WebElement”对象没有属性“getText”。谢谢您提供的线索,请解决它!您的代码将无法工作,因为您使用的
find_elements
(复数)将引发错误。此外,您的定位器对于所有级别和索引都非常脆弱。您应该接受(并使用)QHarr的答案。定位器不那么脆弱,代码也能正常工作。谢谢,
find_elements
是一个打字错误,我实际上最终使用了
find_element
。不过,我接受了QHarr的答案。谢谢!
codes = driver.find_elements(By.XPATH, "//*[@id=\"page-wrapper\"]/div[2]/div[2]/center/form/div/label[2]").text