所以我有一个网络爬虫,它打印出给定站点的所有链接,而不重复相同的链接。我的代码(带有导入但尚未使用的库)如下所示:
import urllib
import re
import mechanize
from bs4 import BeautifulSoup
import urlparse
import cookielib
from urlparse import urlsplit
from publicsuffix import PublicSuffixList
url = "http://www.zahnarztpraxis-uwe-krause.de"
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
br.set_handle_robots(False)
br.set_handle_equiv(False)
br.set_handle_redirect(True)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
page = br.open(url, timeout=5)
htmlcontent = page.read()
soup = BeautifulSoup(htmlcontent)
newurlArray = []
for link in br.links(text_regex=re.compile('^((?!IMG).)*$')):
newurl = urlparse.urljoin(link.base_url, link.url)
if newurl not in newurlArray:
newurlArray.append(newurl)
print newurl
它给了我这样的结果:
.....
http://www.zahnarztpraxis-uwe-krause.de/pages/amalgamentfernung.html
http://www.zahnarztpraxis-uwe-krause.de/pages/homoeopathie.html
http://www.zahnarztpraxis-uwe-krause.de/pages/veneers.html
http://www.zahnarztpraxis-uwe-krause.de/pages/prophylaxe.html
http://www.zahnarztpraxis-uwe-krause.de/pages/bleaching/bleaching-zahnschmuck.html
http://www.zahnarztpraxis-uwe-krause.de/pages/dental_wellness_care.html
http://www.zahnarztpraxis-uwe-krause.de/pages/digitales-roentgen.html
http://www.zahnarztpraxis-uwe-krause.de/pages/anfahrt.html
http://www.zahnarztpraxis-uwe-krause.de/pages/kontakt.html
http://www.zahnarztpraxis-uwe-krause.de/pages/impressum.html
etc....
现在我的问题是如何告诉我的程序它只打印出包含单词kontakt
的链接。
我应该为此使用正则表达式还是其他什么?
我从来没有这样做过,所以我不知道用什么来获得唯一的结果:
http://www.zahnarztpraxis-uwe-krause.de/pages/kontakt.html
有什么建议么?