regex - 使用 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:
- 如果 searchString = "Foo" -> 匹配
- 如果 searchString = "Bar" -> 匹配
- 如果 searchString = "Foo(.)*Bar" -> 不匹配
- 如果 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”,但不确定它们之间可能会放置什么。
有什么想法我做错了吗???
解决方案
好的 - 这就是我解决它的方法 - 感谢@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)
推荐阅读
- jquery - 在函数结束时重复函数
- java - Maven - 在编译时发现类类型
- python - 如何平滑 z 值并减少其在 python 中的变化?
- php - 使用 html encode(yii2) 显示数据库中的数据
- python - 带有 python 子进程的 WSL
- nlp - 有没有办法将 spacy 标签列入白名单?
- google-apps-script - 无法在 Google 表格中设置值
- php - 在 WooCommerce 电子邮件通知中将发件人姓名更改为客户账单全名
- html - 是否可以在 transform: translateX 中使用 %vw?
- python - pybind11:通过值/引用将 numpy 数组传递给 c++