擅长:python、mysql、java
<p>颠倒逻辑,得到所有的<code>section.sneaker-post-main</code>,然后使用它作为dict中分组的键来查找前一个兄弟:</p>
<pre><code>import requests
from collections import defaultdict
cont = requests.get(url, headers=ua).content
soup = BeautifulSoup(cont,"lxml")
d = defaultdict(list)
sections = soup.select("div.release-post-list section.sneaker-post-main")
for section in sections:
h4 = section.find_previous_sibling("h4",{"class":"month-header"})
d[h4.text.strip()].append(section)
print(d["April 15, 2016"])
</code></pre>
<p>使用第一个标题文本作为键,您可以看到正确的前三个<code>sneaker-post-main</code>:</p>
^{pr2}$
<p>每个<code>h4.month-header</code>可以有很多<code>section.sneaker-post-main</code>同级,但是每个<code>section.sneaker-post-main</code>只有一个与其部分相关的前一个<code>h4.month-header</code>同级。在</p>