【发布时间】: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