遍历表行并使用Python打印a href文本

2024-05-16 03:23:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我的总体目标是遍历这个表中的每个tr,遍历每个td的几个tr,并打印出其中的文本。你知道吗

我试着回到尸体的地方,但还是没有找到。理想情况下,我只想通过table[@id='aui']/tbody/tr[i]/td[i]运行一个for循环,其中i是范围内的变量(0,sizeOfTable)

ele = driver.find_elements_by_xpath("//body/div[@id='page']/section[@id='content']/div[@class='aui-page-panel']/div[@class='aui-page-panel-inner']/section[@class='aui-page-panel-content']/div[@class='aui-page-panel']/div[@class='aui-page-panel-inner']/section[@class='aui-page-panel-content']/div[@class='module']/div[@id='projects']/div[@class='p-list']/table[@id='aui']/tbody/tr[1]/td[1]")

现在,当我在创建ele之后运行print(ele.text)时,它只打印出一个空列表

this is the html I'm working off of:


Tags: dividpagetablesectioncontenttrclass
1条回答
网友
1楼 · 发布于 2024-05-16 03:23:39

问题的原因是XPath错误。表中有classaui,但没有id。你知道吗

更正XPath如下。你知道吗

  //table[@class='aui']//tr

这应该给您一个行列表,然后您可以遍历它们。你知道吗

脚本:如果要打印单元格中的文本,请使用此命令。你知道吗

rows = driver.find_element_by_css_selector("table.auti  tr")
for row in rows:
    # get the hrefs
    columsWithLink = row.find_element_by_xpath(".//td[a]")
    for column in columsWithLink:
        # print column text
        print (column.text)
        # print link href
        print(column.find_element_by_xpath(".//a").get_attribute("href"))

脚本:如果您只想打印链接HREF,请使用下面的

rows = driver.find_element_by_css_selector("table.auti  tr")
for row in rows:
    # get the hrefs
    links = row.find_element_by_xpath(".//td/a")
    for link in links:
        # print link href
        print(link.get_attribute("href"))

相关问题 更多 >