Python Selenium如何获取父元素

时间:2019-10-12 14:56:25

标签: python selenium selenium-webdriver web-scraping

我想在“道路”上找到文字并在图片中找到位置的父级。 a busy cat

My code get to "Road" text. but can't get to parent of position element
 T4 = driver.find_element_by_css_selector('table#tableID4')
 T4.text

Output: 'Road\nRoad\n2\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad\nRoad'

html标记:

<table id="tableID4">
            <tr id="bigTr"><td id="bigRoadTd_0_0" class="">
                                    <p style="display: none"></p>
                                    <div style="" class="tie"></div>
                                    <div style="display: none" class=""></div>
                                    <div style="display: none" class=""></div>
                                    <div style="display: none" class=""></div>
                                    <div style="" class="banker">Road</div>
                                </td><td id="bigRoadTd_1_0" class="">
                                    <p style="display: none"></p>
                                    <div style="display: none" class=""></div>
                                    <div style="display: none" class=""></div>
                                    <div style="display: none" class=""></div>
                                    <div style="display: none" class=""></div>
                                    <div style="" class="player">Road</div>

1 个答案:

答案 0 :(得分:1)

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(driver, 3).until(
                        EC.presence_of_element_located((By.ID , 'bigRoadTd_0_0')))

parent = driver.find_element(By.ID,'bigRoadTd_0_0')
all_children = parent.find_elements(By.TAG_NAME,"div")
for child in all_children:
    print(child.get_attribute('outerHTML'))

以上将找到父级并解析子级的外部HTML。

此外,您不会使用css选择器来找到该特定子元素,而是:

element_html = driver.find_element(By.CLASS_NAME,'banker').get_attribute('outerHTML')

这些是按类可用的属性:

ID = "id"
XPATH = "xpath"
LINK_TEXT = "link text"
PARTIAL_LINK_TEXT = "partial link text"
NAME = "name"
TAG_NAME = "tag name"
CLASS_NAME = "class name"
CSS_SELECTOR = "css selector"
相关问题