找到具有beautifulsoup的具体链接

Jen*_*ott 10 python regex beautifulsoup

嗨,我无法弄清楚如何找到以我的生命中某些文字开头的链接.findall('a')工作得很好,但是太过分了.我只想列出以http://www.nhl.com/ice/boxscore.htm?id=开头的所有链接

谁能帮我?

非常感谢你

jte*_*ace 12

首先设置一个测试文档并使用BeautifulSoup打开解析器:

>>> from BeautifulSoup import BeautifulSoup
>>> doc = '<html><body><div><a href="something">yep</a></div><div><a href="http://www.nhl.com/ice/boxscore.htm?id=3">somelink</a></div><a href="http://www.nhl.com/ice/boxscore.htm?id=7">another</a></body></html>'
>>> soup = BeautifulSoup(doc)
>>> print soup.prettify()
<html>
 <body>
  <div>
   <a href="something">
    yep
   </a>
  </div>
  <div>
   <a href="http://www.nhl.com/ice/boxscore.htm?id=3">
    somelink
   </a>
  </div>
  <a href="http://www.nhl.com/ice/boxscore.htm?id=7">
   another
  </a>
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

接下来,我们可以搜索<a>具有以... href开头的属性的所有标签http://www.nhl.com/ice/boxscore.htm?id=.您可以使用正则表达式:

>>> import re
>>> soup.findAll('a', href=re.compile('^http://www.nhl.com/ice/boxscore.htm\?id='))
[<a href="http://www.nhl.com/ice/boxscore.htm?id=3">somelink</a>, <a href="http://www.nhl.com/ice/boxscore.htm?id=7">another</a>]
Run Code Online (Sandbox Code Playgroud)