Skip to main content
 首页 » 编程设计

python之正则表达式匹配的问题

2025年05月04日30小虾米

我目前正在学习 Python,我正在尝试制作一个小的刮板,但我遇到了 Beautiful Soup 和正则表达式的问题。

我正在尝试匹配具有以下 html 的站点中的所有链接:

<td> 
    <a href="/l1234/Place+Number+1">Place Number 1 </a> 
</td> 
<td width="100"> 
    California  </td> 
<td> 
    <a href="/l2342/Place+Number+2">Place Number 2 </a> 
</td> 
<td width="100"> 
    Florida </td> 

我想获取以下所有链接:“/lxxxx/Place+Number+x”

我为此使用了 python 和 beautifulsoup:

import BeautifulSoup 
import urllib2 
import re 
 
address = 'http://www.example.com' 
 
html = urllib2.urlopen(address).read() 
 
soup = BeautifulSoup(html) 
 
for tag in soup.findAll('a', id = re.compile('l[0-9]*')): 
    print tag['href'] 

我在一些示例代码中找到的 soup.findAll 中的正则表达式部分,因为我似乎无法让 BeautifulSoup 文档中的示例正常工作。没有正则表达式部分,我得到了页面上的所有链接,但我只想要“lxxx”的

我的正则表达式做错了什么?也许没有正则表达式就可以做到这一点,但我似乎找不到办法。

请您参考如下方法:

你不应该尝试在 href 而不是 id 上进行正则表达式匹配吗?

for tag in soup.findAll('a', href = re.compile('l[0-9]*')): 
    print tag['href']