最近用python做了个小crawler, 可以自动整理一些网站的内容,推送到当地文件中,做个小小的总结。
主要lib就是urllib 和 beautifulsoup.
urllib和urllib2是很方便的网页提取库,核心就是发送各种自定义的url request,然后可以返回网页内容。 最简单的函数,判定一个网页是否存在:
def isUrlExists(url):
req = urllib2.Request(url, headers=headers)
try:
urllib2.urlopen(req)
except:
return 0;
return 1;
headers可以自定义,也可以留空。自定义的主要目的是模仿成一般浏览器的header,绕过一些网站对crawler的封锁。
如果想获得网站内容,并且获取返回异常的内容,可以这样:
def fetchLink(url):
req = urllib2.Request(url, headers=headers)
try:
response = urllib2.urlopen(req)
except urllib2.URLError, e:
print 'Got Url Error while retrieving: ', url, ' and the exception is: ', e.reason
except urllib2.HTTPError, e:
print 'Got Http Error while retrieving: ',