【问题标题】:How to use re with beautifulsoup in python 2.7 to suppress certain results?如何在 python 2.7 中使用 re 和 beautifulsoup 来抑制某些结果?
【发布时间】:2018-06-11 08:23:03
【问题描述】:

我正在尝试使用 beautifulsoup 和 re 来获取 URL 列表,但我想抑制其中一个结果,但我不知道该怎么做。

这段代码为我提供了 29 个(共 35 个)网址:

issue_index = soup.find_all('a', href=re.compile('past'))

这太多了。

其中一个 URL 包含 target="_blank",我想从其他 URL 中排除此 URL。

但是,我不知道该怎么做。

这与我想要的完全相反,只返回我想要丢弃的 URL。

issue_index = soup.find_all('a', href=re.compile('past'), target="_blank")

此代码删除了错误的 URL(带有 target 属性),但它没有使用正则表达式过滤列表。

def remove(a):
    return a.has_attr('href') and not a.has_attr('target')

issue_index = soup.find_all(remove)

这太疯狂了。

【问题讨论】:

  • 真的,毫无头绪的投反对票。

标签: python regex python-2.7 beautifulsoup


【解决方案1】:

最简单、最直接的方法是过滤掉find_all之后不需要的标签:

issue_index = soup.find_all('a', href=re.compile('past'))
issue_index = filter(lambda tag: tag.attrs.get('target') != '_blank', issue_index)
for tag in issue_index:
    print(tag)

第二种方法是将简单的第一个参数('a')替换为过滤函数:

def a_not_blank(tag):
    return tag.name == 'a' and tag.attrs.get('target') != '_blank'

issue_index = soup.find_all(a_not_blank, href=re.compile('past'))
for tag in issue_index:
    print(tag)

第三种方法是全力以赴,使用单一的过滤功能:

def myfilter(tag):
    pattern = re.compile('past')
    return tag.name == 'a' \
            and tag.has_attr('href') \
            and re.match(pattern, tag.attrs['href']) \
            and tag.attrs.get('target') != '_blank'

soup = BeautifulSoup(html, 'lxml')
for tag in soup.find_all(myfilter):
    print(tag)

【讨论】:

  • 非常感谢您提供如此有用的答案!我正在梳理文档,但没有提出任何建议。我使用的是第一种方法,但这些功能非常适合学习。
猜你喜欢
  • 2013-01-16
  • 2014-12-01
  • 2021-02-12
  • 2020-11-01
  • 1970-01-01
  • 2020-08-14
  • 2022-12-13
  • 1970-01-01
  • 2017-04-19
相关资源
最近更新 更多