首页 > 解决方案 > 使用 RegEx 和 Beautiful Soup 查找锚文本 - RegEx 无法按预期工作

问题描述

我正在尝试使用 Beautiful Soup 在页面的链接中使用 RegEx 搜索文本中的关键字。

<a href="/company/05835190" onclick="javascript:_paq.push(['trackEvent', 'SearchSuggestions', 'SearchResult-1' ]);" title="View company"><strong>FOO</strong>blah blah<strong>BAR</strong>example</a>

这是我的简单代码:

raw_html = simple_get(searchString) 
searchString = ...see below...

if len(str(raw_html)) != 0:
    html = BeautifulSoup(raw_html, 'html.parser')
    companyLink = html.find_all('a', string=re.compile(searchString, 
    re.IGNORECASE))
    print(companyLink)

假设链接文本是:Foo blah blah bar:

  1. 如果 searchString = "Foo" -> 匹配
  2. 如果 searchString = "Bar" -> 匹配
  3. 如果 searchString = "Foo(.)*Bar" -> 不匹配
  4. 如果 searchString = "Foo blah blah bar" -> 不匹配!(我什至直接从网页上复制了文字)

我试过 companyLink = html.find_all('a', text=re.compile(searchString, re.IGNORECASE)) - 不行

我试过 companyLink = html.find_all(string=re.compile(searchString, re.IGNORECASE)) - 不行

我试过 companyLink = html.find_all(text=re.compile(searchString, re.IGNORECASE)) - 不行

我认为所有四个版本的 searchString 都应该返回一个匹配项。我真的很想使用第 3 版,因为我知道“Foo”和“Bar”,但不确定它们之间可能会放置什么。

有什么想法我做错了吗???

标签: regexpython-3.xbeautifulsoup

解决方案


好的 - 这就是我解决它的方法 - 感谢@Wiktor Stribiżew 帮助破解代码:

<a href="/company/05835190" onclick="javascript:_paq.push(['trackEvent', 'SearchSuggestions', 'SearchResult-1' ]);" title="View company"><strong>FOO</strong>blah blah<strong>BAR</strong>example</a>

companyName = 'Foo Bar'
searchTarget = re.compile(companyName, re.IGNORECASE)
raw_html = simple_get(searchString)

if len(str(raw_html)) != 0:
#run BeautifulSoup on the page HTML
   html = BeautifulSoup(raw_html, 'html.parser')
#find all links where title='View company'
   anchorTitle = html.find_all('a', title='View company')
#convert to string, remove <strong> tags
   a_tag = str(anchorTitle).replace('<strong>', '')
#remove </strong> tags
   a_tag = a_tag.replace('</strong>', '')
#remove multiple spaces
   a_tag = re.sub('( ){2,}',' ', a_tag)
#run BeautifulSoup again on the edited string
   b_tag = BeautifulSoup(a_tag, 'html.parser')
#find link where string = 'Foo Bar'
   anchorText = b_tag.find('a', string=searchTarget)

   print(anchorText)

推荐阅读