簡體   English   中英

Python Selenium無法通過xpath查找表元素

[英]Python Selenium unable to find table element by xpath

這是網頁上表格的外觀(僅一列):

這是表格在網頁上的樣子

這是我要抓取的表格的HTML:

這是我要抓取的表格的HTML

如果重要的話,該表將嵌套在另一個表中。

這是我的代碼:

    def filter_changed_records():
        # Scrape webpage for addresses from table of changed properties
        row_number = 0
        results_frame = locate_element(
            '//*[@id="oGridFrame"]'
        )
        driver.switch_to.frame(results_frame)
        while True:
            try:
                address = locate_element("id('row" + str(row_number) +
                                         "FC')/x:td")
                print(address)
                changed_addresses.append(address)
                row_number += 1
            except:
                print("No more addresses to add.")
                break

如您所見,有一個<tr>標記,其id為row0FC 該表是動態生成的,每個新的<tr>都獲得一個ID,其ID的數字遞增: row0FC, row1FC, row2FC等。這就是我計划遍歷所有條目並將其添加到列表中的計划。

我的locate_element函數如下:

    def locate_element(path):
        element = WebDriverWait(driver, 50).until(
            EC.presence_of_element_located((By.XPATH, path)))
        return element

由於找不到元素,它總是在50秒后超時。 不確定如何進行。 有沒有更好的定位元素的方法?

安德森的解決方案

address = locate_element("//tr[@id='row%sFC']/td" % row_number).text

您的XPath似乎不正確。

請嘗試以下方法:

address = locate_element("//tr[@id='row%sFC']/td" % row_number)

還要注意, addressWebElement 如果要獲取其文本內容,則應使用

address = locate_element("//tr[@id='row%sFC']/td" % row_number).text

用硒分析html很慢。 我會為此使用BeautifulSoup。

假設您已將頁面加載到驅動程序中,則該過程類似於:

from bs4 import BeautifulSoup
....

soup = BeautifulSoup(driver.page_source, "html.parser")
td_list = soup.findAll('td')
for td in td_list:
    try:
        addr = td['title']
        print(addr)
    except:
        pass

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM