我寫過一個庫,它通過從維基百科中提取href鏈接並保存它們來創建一個持久層。我意識到我有一個鏈接,我不關心那個標籤爲/wiki/Cookbook:Table_of_Contents
。與不需要的鏈接匹配
模仿!~
(不匹配)並保持Pythonic的最佳方式是什麼?
爲了更好的上下文和理解,我會解決這個問題,像這樣的紅寶石:
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'])]
爲什麼downvote?我只是在尋找第二種意見或更好的選擇,而不是釣魚竿。 – theGrayFox 2014-10-06 22:19:46