更简单的python客户端库
zester的Python项目详细描述
Zester是一个库,它使为没有API的网站开发Python客户端变得更加容易。
没有lxml,没有xpath,只有javascript。
通过将以下代码保存在名为hnclient.py的文件中,让我们为Hacker News创建一个客户机库:
from zester import MultipleClient, Attribute class HNClient(MultipleClient): url = "http://news.ycombinator.com/" title = Attribute(selector="$('.title a')", modifier="$(el).html()") link = Attribute(selector="$('.title a')"), modifier="$(el).attr('href')") points = Attribute(selector="$('.subtext span')", modifier="$(el).html().replace(' points', '')")
现在,让我们用我们刚做的客户。打开python外壳:
>>> from hnclient import HNClient >>> client = HNClient() >>> stories = client.process() >>> stories[0] HNClientResponse(points=u'200', link=u'http://daltoncaldwell.com/what-twitter-could-have-been', title=u'What Twitter could have been') >>> print stories[0].title What Twitter could have been >>> print stories[0].link http://daltoncaldwell.com/what-twitter-could-have-been >>> print stories[0].points 56
我们在那里细分了multipleclient,因为我们计划返回多个结果。如果我们想为返回一个结果的Weather.gov之类的东西创建一个客户机,我们可以这样做:
from zester import SingleClient, Attribute class WeatherClient(SingleClient): url = "http://forecast.weather.gov/MapClick.php?lat={lat}&lon={lng}" temperature = Attribute(selector="$('.myforecast-current-lrg').html()") humidity = Attribute(selector="$('.current-conditions-detail li').contents()[1]") heat_index = Attribute(selector="$('.current-conditions-detail li').contents()[11]") def __init__(self, lat, lng, *args, **kwargs): super(WeatherClient, self).__init__(*args, **kwargs) self.url = self.url.format(lat=lat, lng=lng)
这还演示了如何允许获取参数:
>>> from weather_client import WeatherClient >>> client = WeatherClient(lat=40.7143528, lng=-74.0059731) >>> curr_weather = client.process() >>> curr_weather WeatherClientResponse(heat_index=u'82\xb0F (28\xb0C)', temperature=u'80\xb0F', humidity=u'58%') >>> print curr_weather.temperature 80°F >>> print curr_weather.humidity 58% >>> print curr_weather.heat_index 82°F (28°C)
安装
泽斯特依赖于Ghost.py。在安装Zester之前必须安装它。ghost.py还需要安装pyqt或pyside。
安装ghost.py后,要安装Zester:
$ pip install zester