【问题标题】:Matching Against Unwanted Links匹配不需要的链接
【发布时间】:2014-10-07 06:24:49
【问题描述】:

我编写了一个库,它通过从 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'])]

【问题讨论】:

  • 为什么投反对票?我只是在寻找第二个意见或更好的选择,而不是钓鱼竿。

标签: python html web-scraping html-parsing beautifulsoup


【解决方案1】:

有多种方法可以排除不需要的链接。

一种选择是pass a functionhref 参数值中:

soup.find_all('a', href=lambda x: 'Table_of_Contents' not in x)

这将过滤掉a 属性中没有Table_of_Contentshref 标记。

例子:

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']

【讨论】:

  • +1 用于文档链接。我从来没有想过将 href 传递给一个函数,但是在考虑它之后,只要它返回一个布尔值,它就是合法的。你是怎么想到这个主意的?!非常聪明。
  • @TheGrayFox 是的,这就是让这个标签汤变得美丽的原因——它是一个很棒的图书馆。你越熟悉它——你就越意识到它是 python 中最方便和最令人愉快的库之一。而且,仅供参考,您也可以将compiled regex pattern 作为参数值传递:soup.find_all('a', href=re.compile(r'my_pattern_here'))。谢谢。
  • 感谢您的提示,我会清理它。
猜你喜欢
  • 2015-05-22
  • 2021-04-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-27
  • 1970-01-01
  • 2017-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多