2014-02-19 44 views
1

我正在使用python with BeautifulSoup 4来查找匹配特定正则表达式的html页面中的链接。我能够找到与正则表达式匹配的链接和文本,但两者结合在一起将无法正常工作。这里是我的代码:我的汤怎么了?

import re 
import bs4 

s = '<a href="javascript://">Sign in&nbsp;<br /></a>' 

soup = bs4.BeautifulSoup(s) 

match = re.compile(r'sign\s?in', re.IGNORECASE) 

print soup.find_all(text=match) # [u'Sign in\xa0'] 
print soup.find_all(name='a')[0].text # Sign in  

print soup.find_all('a', text=match) # [] 

评论是输出。正如你所看到的,组合搜索没有结果。这很奇怪。

似乎与链接文本中包含的“br”标记(或通用标记)有关。如果删除它,一切都按预期工作。

+0

in引人注目的是,下面的工作:print soup.find_all('a')[0] .find_all(text = match)它返回,[u'登录\ xa0'] – Totem

回答

0

你可以查找标签查找其文字内容却不能在一起:

因为:

self.name = u'a' 
self.text = SRE_Pattern: <_sre.SRE_Pattern object at 0xd52a58> 

source

# If it's text, make sure the text matches. 
elif isinstance(markup, NavigableString) or \ 
     isinstance(markup, basestring): 
    if not self.name and not self.attrs and self._matches(markup, self.text): 
     found = markup 

,使@Totem评论道路设计