Skip to main content
 首页 » 编程设计

python之Selenium 驱动程序 : find elements by xpath; how do i parse a level 2 table (i. e.表中表)

2024年11月01日17youxin

我问了一个问题让我走到这一步 here ,除了因为这是一个具体的不同问题,所以我将其分开,但如果这不是正确的地方,请告诉我。

我有这个脚本:

from selenium import webdriver 
from bs4 import BeautifulSoup 
import os 
from selenium.webdriver.support.ui import Select 
from selenium.webdriver.common.by import By 
from selenium.webdriver.chrome.options import Options 
 
 
options = Options() 
options.binary_location=r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe' 
options.add_experimental_option('excludeSwitches', ['enable-logging']) 
driver = webdriver.Chrome(options=options,executable_path='/mnt/c/Users/kela/Desktop/selenium/chromedriver.exe') 
 
#get the url 
driver.get('http://147.8.185.62/services/NutriChem-2.0/') 
 
 
#find the food name 
element = driver.find_element_by_id("input_food_name") 
element.send_keys("22663") 
 
 
#click food-disease association 
element = Select(driver.find_element_by_css_selector('[name=food_search_section]')) 
element.select_by_value('food_disease') 
 
 
#click submit and click plant-disease associations 
driver.find_element_by_css_selector('[value="Submit"]').click() 
driver.switch_to.frame(driver.find_element_by_css_selector('frame')) 
driver.find_element_by_css_selector('[onclick*="plant-disease"]').click() 
 
 
#to click into each drop down table rows 
driver.switch_to_default_content() 
driver.switch_to.frame(driver.find_element_by_name('mainFrame')) 
driver.switch_to.frame(driver.find_element_by_name('ListWeb')) 

这让我进入了我想要抓取的页面 :

下一阶段,对于每个灰色框,我想提取 (1) PMID ID,(2) 植物,(3) 方向(由图像是 up_arrow.png 还是 down_arrow.png 表示,所以只打印图像名称就可以了)和 (4) 疾病。

正如您从我之前的问题中看到的那样,我对 selenium 很陌生,我想一旦我到了这个阶段,我就会循环遍历表格行并用 beautifulSoup 打印这些行。我的问题的简短版本是我无法让它工作。

我尝试过的事情:

尝试 1:

rows = driver.find_elements_by_xpath("//table[@class='Level1Table']//tr[contains(@name,'hList')]") 
test_row = rows[0] 
print(test_row.text) 

上面的代码将打印“Pomegranate Osteoartritis 3”;但后来我不知道如何在其中循环(我只得到空数据)。

尝试 2: 然后我尝试遍历行中的每个 r ,但这仍然只给我 1 级数据。 (即只打印多行尝试 1)。

尝试 3:

rows = Select(driver.find_elements_by_xpath("//table[@class='Level2Table']//tr[contains(@name,'hList')]")) 
print(rows) 

上面,我想知道为什么我不能像尝试 1 一样运行,而是循环遍历 2 级表而不是 1 级表。此输出为空。我不确定为什么这不起作用;我可以通过检查页面看到 level2table 在那里。

尝试 4: 这是我最初想做的方式,但它不起作用:

for row in rows.findAll('tr'): 
        food_source = row.find_all('td')[1].text 
        pmid = row.find_all('td')[0].text 
        disease = row.find_all('td')[3].text 
        #haven't figured out how to get the association direction yet 
        print(food_source + '\t' + pmid + '\t' + disease + '\t' + association) 

这是我的第一个 selenium 脚本,所以此时我无法理解。有人可以告诉我如何在 1 级表中遍历 2 级表并提取所需的信息(引用、植物、方向和疾病)。

编辑 1:根据下面盖伊的建议,这是完整的脚本:

from selenium import webdriver 
from bs4 import BeautifulSoup 
import os 
from selenium.webdriver.support.ui import Select 
from selenium.webdriver.common.by import By 
from selenium.webdriver.chrome.options import Options 
import pandas as pd 
 
options = Options() 
options.binary_location=r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe' 
options.add_experimental_option('excludeSwitches', ['enable-logging']) 
driver = webdriver.Chrome(options=options,executable_path='/mnt/c/Users/kela/Desktop/selenium/chromedriver.exe') 
 
#get the url 
driver.get('http://147.8.185.62/services/NutriChem-2.0/') 
 
 
#find the food name 
element = driver.find_element_by_id("input_food_name") 
element.send_keys("22663") 
 
 
#click food-disease association 
element = Select(driver.find_element_by_css_selector('[name=food_search_section]')) 
element.select_by_value('food_disease') 
 
 
#click submit and click plant-disease associations 
driver.find_element_by_css_selector('[value="Submit"]').click() 
driver.switch_to.frame(driver.find_element_by_css_selector('frame')) 
driver.find_element_by_css_selector('[onclick*="plant-disease"]').click() 
 
 
#to click into each drop down table rows 
driver.switch_to_default_content() 
driver.switch_to.frame(driver.find_element_by_name('mainFrame')) 
#driver.switch_to.frame(driver.find_element_by_name('ListWeb')) 
 
#rows = driver.find_elements_by_xpath("//table[@class='Level1Table']//tr[contains(@name,'hList')]") 
#test_row = rows[0] 
 
driver.switch_to.frame('ListWeb') # no need for find_element, name or id are sufficient 
rows = driver.find_elements_by_css_selector('[id^="ListTAXID"] [name^="Item"]') 
for row in rows: 
        row_data = row.find_elements_by_xpath('.//td') 
        pmid = row_data[0].text 
        plant = row_data[1].text 
        direction = row_data[2].get_attribute('src') 
        disease = row_data[3].text 
        print(str(pmid) + '\t' + str(plant) + '\t' + str(direction) + '\t' + str(disease)) 

这导致了这个输出:

        None 
        None 
        None 
        None 
        None 
        None 
        None 
        None 
        None 
        None 
        None 
        None 

请您参考如下方法:

内表不是标题行的一部分(带有 'Pomegranate Osteoartritis 3' 文本),而是在不可见的同级行内。

这些行具有以 ListTAXID 开头的 id 属性,可以帮助识别它们,并且您要查找的数据在具有 name< 的后代元素中 开始 Item 的属性。

文本仅在表格打开时可用。你可以在收集数据之前点击所有的标题行,或者使用get_attribute('innerText')代替text,即使表格还在,它也会获取数据关闭。

driver.switch_to.frame('ListWeb') # no need for find_element, name or id are sufficient 
 
rows = driver.find_elements_by_css_selector('[id^="ListTAXID"] [name^="Item"]') 
for row in rows: 
    row_data = row.find_elements_by_xpath('.//td') 
    pmid = row_data[0].get_attribute('innerText') 
    plant = row_data[1].get_attribute('innerText') 
    direction = 'up_arrow' if 'up_arrow' in row_data[2].find_element_by_xpath('.//img').get_attribute('src') else 'down_arrow' 
    disease = row_data[3].get_attribute('innerText') 

作为旁注,您应该最大化窗口 driver.maximize_window()