我的例子是html
<li><h4>A0: Pronouns</h4></li>
<li class="">
<a>bb</a>
<a>cc</a>
</li>
<li class="">
<a>dd</a>
<a>ee</a>
</li>
<li><h4>A0: Verbs Tenses & Conjugation</h4></li>
<li class="">
<a>ff</a>
<a>gg</a>
</li>
<li class="">
<a>hh</a>
<a>kk</a>
</li>
<li class="">
<a>jj</a>
<a>ii</a>
</li>
对于每个元素<li class=""><a>
,我想找到其最近的上面的兄弟元素<li><h4>
。比如说,
<li class=""><a>bb</a></li>
对应于<li><h4>A0: Pronouns</h4></li>
<li class=""><a>dd</a></li>
对应于<li><h4>A0: Pronouns</h4></li>
<li class="">ff<a>dd</a></li>
对应于<li><h4>A0: Verbs Tenses & Conjugation</h4></li>
<li class="">hh<a>dd</a></li>
对应于<li><h4>A0: Verbs Tenses & Conjugation</h4></li>
<li class="">jj<a>dd</a></li>
对应于<li><h4>A0: Verbs Tenses & Conjugation</h4></li>
你能详细说明一下怎么做吗
import requests
from bs4 import BeautifulSoup
session = requests.Session()
headers = {
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'en-US,en;q=0.8',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
}
link = 'https://french.kwiziq.com/revision/grammar'
r = session.get(link, headers = headers)
soup = BeautifulSoup(r.content, 'html.parser')
for d in soup.select('.callout-body > ul li > a:nth-of-type(1)'):
print(d)
您可以使用
.find_previous('h4')
:印刷品:
您可以在CSS路径中使用
:is
:输出:
输出存储与语法部分关联的每个
li
的第一个a
。如果您只想在组件结果中使用1-1
部分,则可以使用字典理解:输出:
相关问题 更多 >
编程相关推荐