相关疑难解决方法(0)

BeautifulSoup:如何从包含一些嵌套<ul>的<ul>列表中提取所有<li>?

我的源代码如下:

<h3>Header3 (Start here)</h3>
<ul>
    <li>List items</li>
    <li>Etc...</li>
</ul>
<h3>Header 3</h3>
<ul>
    <li>List items</li>
    <ul>
        <li>Nested list items</li>
        <li>Nested list items</li></ul>
    <li>List items</li>
</ul>
<h2>Header 2 (end here)</h2>
Run Code Online (Sandbox Code Playgroud)

我希望所有"li"标签跟在第一个"h3"标签之后,并停在下一个"h2"标签,包括所有嵌套的li标签.

firstH3 = soup.find('h3')

正确找到我想要开始的地方.

firstH3 = soup.find('h3') # Start here
uls = []
for nextSibling in firstH3.findNextSiblings():
    if nextSibling.name == 'h2':
        break
    if nextSibling.name == 'ul':
        uls.append(nextSibling)
Run Code Online (Sandbox Code Playgroud)

给我一个UL列表,每个都有我需要的LI内容.

摘录"uls"列表:

<ul>
...
    <li><i><a href="/wiki/Agent_Cody_Banks" title="Agent Cody Banks">Agent Cody Banks</a></i> (2003)</li>
    <li><i><a href="/wiki/Agent_Cody_Banks_2:_Destination_London" title="Agent Cody Banks 2: Destination London">Agent Cody Banks 2: Destination …
Run Code Online (Sandbox Code Playgroud)

python screen-scraping beautifulsoup

23
推荐指数
2
解决办法
4万
查看次数

标签 统计

beautifulsoup ×1

python ×1

screen-scraping ×1