![](/img/trans.png)
[英]How to extract text and the xpath to that element of the HTML page in Python
[英]How to extract element within a HTML Tag using Xpath in python?
我有一個像這樣的 HTML 標簽
<tr class="js-row DC is-odd" data-nationality="Indian" data-team-id="3">
<td class="top-players__freeze js-pos top-players__pos DC">2</td>
<td class="top-players__freeze top-players__player">
<div class="top-players__image">
<img class="js-headshot" src="//static.iplt20.com/players/210/Photo-Missing.png"
我正在嘗試使用 XPath 提取數據國籍值,但是我不太確定如何執行此操作。
在選擇 tr 元素后,我嘗試過這樣的事情:
driver.find_elements_by_xpath("//tr[contains(@class,'js-row DC is-odd')]/@data-nationality")
然而這並沒有奏效。 有人可以幫我解決這個問題嗎?
嘗試使用get_attribute()
元素方法。
driver.find_element_by_xpath("//tr[contains(@class,'js-row DC is-odd')]").get_attribute("data-nationality")
https://www.geeksforgeeks.org/get_attribute-element-method-selenium-python/
看來你已經足夠接近了。 假設class
的值DC和data-team-id="3"
是元素中的兩個唯一屬性值,要打印data-nationality屬性的值,即印度,您需要為visibility_of_element_located()
引入WebDriverWait ,您可以使用以下任一定位器策略:
使用CSS_SELECTOR
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "tr.js-row.DC.is-odd[data-team-id='3']"))).get_attribute("data-nationality"))
使用XPATH
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//tr[@class='js-row DC is-odd' and @data-team-id='3']"))).get_attribute("data-nationality"))
控制台輸出:
Indian
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.