我正在尝试使用 beautifulsoup 获取视频链接(在 vimeo.com 上)。 我设法用下面的代码得到了我想要的东西,但我试图让它更简单,但我不能......
HTML 来源:
<h5 class="m-b-5"><b>Devoirs </b>
</h5>
<p class="text-muted m-b-30 font-13">
N/A </p>
<h5 class="m-b-5"><b>Commentaires sur la performance </b></h5>
<p class="text-muted m-b-30 font-13">
Today finished up the writing and completed the listening assessment. Next week she'll complete the speaking and be
finished! </p>
<h5 class="m-b-5"><b>Lien vers la vidéo </b></h5>
<p class="text-muted m-b-30 font-13">
<a href="https://vimeo.com/zxzzxzx" target="_blank">https://vimeo.com/zxzxzx</a>
</p>
Python 代码:
soup = BeautifulSoup(Session1.text, "lxml")
regex = re.compile('Lien vers la vidéo')
vimeolink=soup.find(string=regex).parent.parent.next_sibling.next_element.next_element.next_element.next_element
# tried the following but it's not working:
# vimeolink=soup.find(string=regex).parent('h5').find_next_sibling('a)
print(vimeolink)
result:
https://vimeo.com/zxzzxz
我尝试使用 find_next_sibling
但没有成功。
最佳答案
尝试:
a = soup.select_one('h5:-soup-contains("Lien vers la vidéo")').find_next("a")["href"]
print(a)
打印:
https://vimeo.com/zxzzxzx
或者:
a = soup.select_one('h5:-soup-contains("Lien vers la vidéo") + p a')["href"]
print(a)
注意:如果您使用旧版本的 bs4
,请将 :-soup-contains
更改为 :contains
关于python - 我无法使用 FIND_NEXT_SIBLING 而不是 PARENT 和 NEXT_ELEMENT 优化 beautifulsoup 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68027596/