如何在爬取过程中 select 项在无序列表中?

How to select item in an unordered list during crawling?

我想抓取 HTML 页面中无序列表中的特定元素。有时,此元素存在,有时不存在。如果该元素存在,我想 select 相应列表项中的第二段。

示例:

<div class="testdiv">
  <ul class="ullist">
    <li><p>random element 1</p><p>value</p></li>
    <li><p>random element 2</p><p>value</p></li> 
    <li><p>element_to_select</p><p>wanted_value</p></li> 
    <li><p>random element 4</p><p>value</p></li>
  </ul>
</div>

对于上面的HTML,我首先要检查是否存在'element_to_select',如果存在,则获取wanted_value。

我尝试了以下(相当幼稚)的方法:

soup_parsed = BeautifulSoup(global_html.encode('utf-8'), 'html.parser')
index_of_wanted_element = self.index_containing_substring([str(s) for s in soup_parsed.find_all("p")], "element_to_select")
wanted_element_paragraph = soup_parsed.find_all("p")[index_of_wanted_element+1]
wanted_value_string = str(wanted_element_paragraph).replace("<p>","").replace("</p>","")

其中 index_containing_substring 在列表中找到所需字符串的索引。

这在 Python 中是否可行,例如,使用 BeautifulSoup、Xpath 等?

想法是通过文本获取element_to_select元素,检查它是否不是None,如果不是,则获取下一个p兄弟元素:

element_to_select = soup.find("p", text="element_to_select")
if element_to_select is not None:
    next_element = element_to_select.find_next_sibling("p")
    print(next_element.get_text())