首页 > 解决方案 > 如何遍历项目列表并使用 Selenium 和 Python 提取特定部分

问题描述

在此处输入图像描述从这个网页“ https://meshb.nlm.nih.gov/treeView ”,我想遍历树的每个节点,如果我在他们的项目中看到“心血管......”这个词,我想创建列出顶级节点以及所有心血管相关项目的字典。例如,在上面的页面中,您可以看到,如果您展开“解剖学 [A]”,您将看到心血管。现在,如果您扩展它,我想要这部分以及心血管中包含的任何内容。我想遍历它的一些元素的html页面的一部分如下:

<a class="ng-scope">
   <span class="ng-binding ng-scope">Anatomy [A]</span>
</a>
    <ul class="treeItem ng-scope">
        <li class ="ng-scope" >
              < a  class ="ng-scope" href="/record/ui?ui=D001829" >
              < span  class ="ng-binding ng-scope" > Body Regions[A01] < / span >
              </a>
        </li>
        < li class ="ng-scope" >
              <a  class ="ng-scope" href="/record/ui?ui=D001829" >
                < span  class ="ng-binding ng-scope" > Cardio Vascular< / span >
              </a>
                    <ul class="treeItem ng-scope">
                        <li class="ng-scope">
                           <a class="ng-scope" href="/record/ui?ui=D015824">
                           <span class="ng-binding ng-scope">Blood-Air Barrier [A07.025]</span>
                           </a>
                                 <ul class="treeItem ng-scope">                    
                                   <li class="ng-scope">
                                       <a class="ng-scope" href="/record/ui?ui=D018916">
                                       <span class="ng-binding ng-scope">Blood-Aqueous Barrier [A07.030]</span>                        
                                       </a>
                                    </li>
                                 </ul>
                        </li>
                    </ul>
        </li>
    </ul>

.....这就是我迄今为止能够完成的!在 Python 中;作为第一步,我想遍历顶层节点并找到“心血管......”这个词,但我一直看到错误“没有这样的元素:无法定位元素”。有人能告诉我我在这里想念什么吗?

from selenium import webdriver
chrome_path=r"G:\My Drive\A\chrome_driver\chromedriver_win32\chromedriver.exe"
driver=webdriver.Chrome(chrome_path)
driver.get('https://meshb.nlm.nih.gov/treeView')
for links in driver.find_elements_by_css_selector('a.ng-scope'):
    cardio = links.find_element_by_css_selector('li>a>span.ng-binding.ng-scope')        
    print(cardio.text)

标签: pythonselenium

解决方案


您的代码中存在一些问题。除非单击父节点上的“+”图标,否则无法遍历列表。

在您的代码中,我可以看到您创建了一个列表,其中包含父节点,如解剖、有机体等,但您还没有编写代码来扩展列表。

您必须遵循的步骤是:

  1. 将父节点存储在列表中 => 此步骤已包含在您的代码中。
  2. 通过单击展开图标(+ 图标)=> 遍历每个父节点需要被覆盖。
  3. 将子节点存储在列表中并遍历子节点 => 需要覆盖
  4. 继续迭代,除非您发现子节点“心血管”=> 需要被覆盖。
  5. 点击子节点“心血管”前面的+图标,将节点“心血管”下的元素存储在字典中=>需要覆盖。

我为您创建了一个涵盖第 1、第 2 和第 3 步的代码。请以同样的方式进行。

from selenium import webdriver
chrome_path=r"G:\MyDrive\A\chrome_driver\chromedriver_win32\chromedriver.exe"
driver=webdriver.Chrome(chrome_path)
driver.get('https://meshb.nlm.nih.gov/treeView')
for links in driver.find_elements_by_css_selector('a.ng-scope'):
    links.find_element_by_xpath("./following-sibling::span/i[1]").click();
      for sublinks in links.find_elements_by_xpath('./following-sibling::ul/li//a'):
        print(sublinks.text)

我有 java 背景,所以请原谅我任何与语言相关的语法问题。


推荐阅读