很高興在GITCAFE遇到了志同道合的人發送了合并請求^_^希望更多的人可以參與進來
寫了很多簡單的Python爬蟲的小例子,今天突然想做個開源的工具包,在gitcafe上和大家一起分享源碼。
項目源地址:
https://gitcafe.com/callmewhy/whyspider
今天寫了個最簡單的功能:GET和POST方法。
其他功能會在gitcafe上陸陸續續的繼續完善,
下一步的計劃是完成正則匹配的封裝和類比header這些常見的功能
因為最近在學安卓,所以更新的進度可能會慢一點=。=
如果有什麼想法,比如覺得希望這個裡面添加什麼功能,歡迎評論或者在gitcafe中提交ticket~
目前剛完成了0.2版本:
# -*- coding: utf-8 -*-#---------------------------------------# 程式:whyspider.py# 版本:0.2# 作者:why# 日期:2014-04-18# 語言:Python 2.7.5## 版本列表:# 0.1:添加GET和POST# 0.2:添加類比頭的功能#---------------------------------------import urllib import urllib2import cookielibimport reimport stringclass WhySpider: # 初始化爬蟲 def __init__(self): self.cookie_jar = cookielib.CookieJar() self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie_jar)) self.headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'} # 發送GET請求 def send_get(self,get_url): result = "" try: my_request = urllib2.Request(url = get_url, headers = self.headers) result = self.opener.open(my_request).read() except Exception,e: print "Exception : ",e return result # 發送POST請求 def send_post(self,post_url,post_data): result = "" try: my_request = urllib2.Request(url = post_url,data = post_data, headers = self.headers) result = self.opener.open(my_request).read() except Exception,e: print "Exception : ",e return result # 類比電腦 def set_computer(self): user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0' self.headers = { 'User-Agent' : user_agent } # 類比手機 def set_mobile(self): user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25' self.headers = { 'User-Agent' : user_agent }
調用方法很簡單:
# -*- coding: utf-8 -*-import whyspider# 初始化爬蟲對象my_spider = whyspider.WhySpider()# 類比GET操作print my_spider.send_get('http://3.apitool.sinaapp.com/?why=GetString2333') # 類比POST操作print my_spider.send_post('http://3.apitool.sinaapp.com/','why=PostString2333') # 類比GET操作print my_spider.send_get('http://www.baidu.com/') # 切換到手機模式my_spider.set_mobile()# 類比GET操作print my_spider.send_get('http://www.baidu.com/')