我编写了一个库,该库通过从Wikipedia提取href链接并保存它们来创建持久层。我意识到,我有一个我不关心的链接被标记为/wiki/Cookbook:Table_of_Contents
。
模拟!~
(不匹配)并保持Pythonic的最佳方法是什么?
为了更好的了解和理解,我将在ruby中解决以下问题:
if link =~ %r{^/wiki/Cookbook} && link !~ /Table_of_Contents/
我的代码:
def fetch_links(self, proxy):
if not self._valid_proxy(proxy):
raise ValueError('invalid proxy address: {}'.format(proxy))
self.browser.set_proxies({'http': proxy})
page = self.browser.open(self.wiki_recipes)
html = page.read()
link_tags = SoupStrainer('a', href=True)
soup = BeautifulSoup(html, parse_only=link_tags)
recipe_regex = r'^\/wiki\/Cookbook'
return [link['href'] for link in soup.find_all('a') if
re.match(recipe_regex, link['href'])]
有多种方法可以排除不需要的链接。
一种选择是在参数值中传递一个函数href
:
soup.find_all('a', href=lambda x: 'Table_of_Contents' not in x)
这将过滤掉属性内a
没有的标签。Table_of_Contents
href
例子:
from bs4 import BeautifulSoup
data = """
<div>
<a href="/wiki/Cookbook:Table_of_Contents">cookbook</a>
<a href="/wiki/legal_link">legal</a>
<a href="http://google.com">google</a>
<a href="/Table_of_Contents/">contents</a>
</div>
"""
soup = BeautifulSoup(data)
print [a.text for a in soup.find_all('a', href=lambda x: 'Table_of_Contents' not in x)]
印刷:
[u'legal', u'google']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句