gpt4 book ai didi

python - 在 python + beautiful soup 上使用正则表达式

转载 作者:太空宇宙 更新时间:2023-11-04 10:35:02 26 4
gpt4 key购买 nike

我有一个这样的 html 页面:

<td class="subject windowbg2">
<div>
<span id="msg_152617">
<a href= SOME INFO THAT I WANT </a>
</span>
</div>
<div>
<span id="msg_465412">
<a href= SOME INFO THAT I WANT</a>
</span>
</div>

如您所见,id="msg_465412"有一个可变数字,所以这是我的代码:

import urllib.request, http.cookiejar,re
from bs4 import BeautifulSoup

contenturl = "http://megahd.me/peliculas-microhd/"
htmll=urllib.request.urlopen(contenturl).read()
soup = BeautifulSoup(htmll)

print (soup.find('span', attrs=re.compile(r"{'id': 'msg_\d{6}'}")))

在最后一行中,我试图找到所有包含 id 的“span”标签,该 id 可以是 msg_######(任意数字),但我的代码有问题,它没有找到任何东西.

P.S: 我想要的所有代码都在一个有 6 列的表中,我想要所有行的第三列,但我认为使用正则表达式更容易

最佳答案

你有点混淆了你的 attrs 参数......目前它是一个包含字典字符串表示的正则表达式,当它需要是一个包含你的属性的字典时'正在搜索其值的正则表达式。

这应该有效:

print (soup.find('span', attrs={'id': re.compile(r"msg_\d{6}")}))

关于python - 在 python + beautiful soup 上使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23839586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com