英文:
Finding a specific span element with a class using Selenium
问题
以下是翻译好的部分:
for elem in driver.find_elements_by_xpath('.//span[@class = "ng-binding"]'):
print(elem.text)
我得到了7个值。
我想要的是第4个值,即:1236 NW 167 ST
我该如何使用DOM层次结构只提取地址项,以便将它们分配给变量?
英文:
The html below is stored in a selenium WebDriver variable
<td colspan="2" class="pi_mailing_address"><strong>Mailing Address</strong>
<div>
<span class="ng-binding">1236 NW 167 ST </span>
<span ng-show="property.mailingAddress.address2" class="ng-binding ng-hide">STE #</span>
<span ng-show="property.mailingAddress.address3" class="ng-binding ng-hide">789</span>
<span ng-show="property.mailingAddress.city" ng-class="{'inline':property.mailingAddress.city}" class="ng-binding inline">OPA LOCKA,</span>
<span class="inline ng-binding">FL</span>
<span class="inline ng-binding">33055-4314</span>
<span ng-hide="isCountryUSA(property.mailingAddress.country)" class="ng-binding"></span>
</div>
</td>
When I run this
for elem in driver.find_elements_by_xpath('.//span[@class = "ng-binding"]'):
print(elem.text)
I get 7 values.
I want the 4 value which is: 1236 NW 167 ST
How would I use the DOM hierarchy to only extract the address items so I can assign then to a variables.
答案1
得分: 2
从第4个<span>
中提取地址,您可以使用以下任一定位策略:
-
使用_CSS_SELECTOR_和
nth-child(4)
:print(driver.find_element(By.CSS_SELECTOR, "td.pi_mailing_address > strong +div span:nth-child(4)").text)
-
使用_CSS_SELECTOR_和
nth-of-type(4)
:print(driver.find_element(By.CSS_SELECTOR, "td.pi_mailing_address > strong +div span:nth-of-type(4)").text)
-
使用_XPATH_和
following
:print(driver.find_element(By.XPATH, "//strong[text()='Mailing Address']//following::div[1]//following::span[4]").text)
-
使用_XPATH_和
following-sibling
:print(driver.find_element(By.XPATH, "//strong[text()='Mailing Address']//following-sibling::div[1]//following::span[4]").text)
-
注意:您需要添加以下导入:
from selenium.webdriver.common.by import By
英文:
To extract the address from the 4<sup>th</sup> <span>
you can use either of the following locator strategies:
-
Using CSS_SELECTOR and
nth-child(4)
:print(driver.find_element(By.CSS_SELECTOR, "td.pi_mailing_address > strong +div span:nth-child(4)").text)
-
Using CSS_SELECTOR and
nth-of-type(4)
:print(driver.find_element(By.CSS_SELECTOR, "td.pi_mailing_address > strong +div span:nth-of-type(4)").text)
-
Using XPATH and
following
:print(driver.find_element(By.XPATH, "//strong[text()='Mailing Address']//following::div[1]//following::span[4]").text)
-
Using XPATH and
following-sibling
:print(driver.find_element(By.XPATH, "//strong[text()='Mailing Address']//following-sibling::div[1]//following::span[4]").text)
-
Note : You have to add the following imports :
from selenium.webdriver.common.by import By
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论