先貼代碼,其它的以后再說
2016.9.23更新瘟判,更改了返回值數(shù)據(jù)類型给郊,當(dāng)請求帶callback參數(shù)時返回jsonp迎罗,否則返回json
urls.py
from django.conf.urls import *
from view import getLocationByName
urlpatterns = [
url(r'^libBook$', getLocationByName),
]
library.py
# -*- coding:utf-8 -*-
__author__='ssins'
from bs4 import BeautifulSoup
import urllib2
import urllib
import re
def getLocationByNo(no):
try:
url = 'http://202.119.252.200:8080/opac/item.php'
values = {'marc_no': no}
data = urllib.urlencode(values)
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
requests = urllib2.Request(url, data, headers)
respond = urllib2.urlopen(requests)
bs = BeautifulSoup(respond.read(), 'lxml')
tr = bs.find('tr', class_='whitetext')
td = tr.find('td', width='25%')
return td.string.strip()
except:
return None
def getNoByName(name):
try:
url = 'http://202.119.252.200:8080/opac/openlink.php'
values = {'title': name}
data = urllib.urlencode(values)
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
requests = urllib2.Request(url, data, headers)
respond = urllib2.urlopen(requests)
bs = BeautifulSoup(respond.read(), 'lxml')
h3 = bs.find('h3')
a = h3.find('a')
return re.search('\d+',a['href']).group()
except:
return None
view.py
# -*- coding:utf-8 -*-
__author__='ssins'
from django.http import HttpResponse
from library import getLocationByNo
from library import getNoByName
import json
def getLocationByName(requset):
name = requset.GET['name']
print type(name)
location = getLocationByNo(getNoByName(name.encode('utf8')))
result = {'location':location}
resultJ = json.dumps(result)
try:
callback = requset.GET['callback']
return HttpResponse(callback + '( ' + resultJ + ' );')
except:
return HttpResponse(resultJ)