kevinweijc 2013-09-28
比urllib好用的requestshttp://www.bsdmap.com/2013/01/13/python-requests/
更多见官方文档:
http://docs.python-requests.org/en/latest/user/quickstart/
http://docs.python-requests.org/en/latest/user/advanced/#advanced
比urllib好用的requests
Python标准库里提供了httplib以及urllib、urllib2,但是学习了好几次,都没有记住(下的功夫不够)。今天崔推荐了一个requests库,看了一下样例,几乎立即就会使用了,所以推荐给大家。
看官方是怎么描述这种情况的:
“Python’sstandardurllib2moduleprovidesmostoftheHTTPcapabilitiesyouneed,buttheAPIisthoroughlybroken.Itwasbuiltforadifferenttime—andadifferentweb.Itrequiresanenormousamountofwork(evenmethodoverrides)toperformthesimplestoftasks.
Thingsshouldn’tbethisway.NotinPython.”
http://docs.python-requests.org/en/latest/
可见urllib2确实不太容易使用。
常用功能罗列如下,以便查询。
#0.认证、状态码、header、编码、json
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}#1.发起请求
import requests URL="http://www.bsdmap.com/" r = requests.get(URL) r = requests.post(URL) r = requests.put(URL) r = requests.delete(URL) r = requests.head(URL) r = requests.options(URL)
#2.通过URL传递参数
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://httpbin.org/get", params=payload)
>>> print r.url
u'http://httpbin.org/get?key2=value2&key1=value1'#3.返回内容
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.text
'[{"repository":{"open_issues":0,"url":"https://github.com/...
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'#4.二进制内容
You can also access the response body as bytes, for non-text requests:
>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...
The gzip and deflate transfer-encodings are automatically decoded for you.
For example, to create an image from binary data returned by a request,
ou can use the following code:
>>> from PIL import Image
>>> from StringIO import StringIO
>>> i = Image.open(StringIO(r.content))#5.JSON
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...#6.超时
>>> requests.get('http://github.com', timeout=0.001)#7.自定义header
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}
>>> r = requests.post(url, data=json.dumps(payload), headers=headers)pyquery:基于python和jquery语法操作XML
http://geoinformatics.cn/lab/pyquery/
Python学习笔记—PyQuery库的使用总结http://newliu.com/post/18/
Python中PyQuery安装http://thend.blog.163.com/blog/static/218973116201349112855661/
Linux下安装Pyquery方法http://blog.xmaoseo.com/451.html
可以使用yumex安装pyquery
一、简介
pyquery库是jQuery的Python实现,可以用于解析HTML网页内容,我个人写过的一些抓取网页数据的脚本就是用它来解析html获取数据的。他的官方文档地址是:http://packages.python.org/pyquery/。今天重新看了一遍整个文档,把它的一些使用方法整理了一下,做个记录。
二、使用方法
frompyqueryimportPyQueryaspq
1.可加载一段HTML字符串,或一个HTML文件,或是一个url地址,例:
d=pq("<html><title>hello</title></html>")
d=pq(filename=path_to_html_file)
d=pq(url='http://www.baidu.com')注意:此处url似乎必须写全
2.html()和text()——获取相应的HTML块或文本块,例:
p=pq("<head><title>hello</title></head>")
p('head').html()#返回<title>hello</title>
p('head').text()#返回hello3.根据HTML标签来获取元素,例:
d=pq('<div><p>test 1</p><p>test 2</p></div>')
d('p')#返回[<p>,<p>]
print d('p')#返回<p>test 1</p><p>test 2</p>
print d('p').html()#返回test 1注意:当获取到的元素不只一个时,html()、text()方法只返回首个元素的相应内容块
4.eq(index)——根据给定的索引号得到指定元素
接上例,若想得到第二个p标签内的内容,则可以:
print d('p').eq(1).html() #返回test 25.filter()——根据类名、id名得到指定元素,例:
d=pq("<div><p id='1'>test 1</p><p class='2'>test 2</p></div>")
d('p').filter('#1') #返回[<p#1>]
d('p').filter('.2') #返回[<p.2>]6.find()——查找嵌套元素,例:
d=pq("<div><p id='1'>test 1</p><p class='2'>test 2</p></div>")
d('div').find('p')#返回[<p#1>, <p.2>]
d('div').find('p').eq(0)#返回[<p#1>]7.直接根据类名、id名获取元素,例:
d=pq("<div><p id='1'>test 1</p><p class='2'>test 2</p></div>")
d('#1').html()#返回test 1
d('.2').html()#返回test 28.获取属性值,例:
d=pq("<p id='my_id'><a href='http://hello.com'>hello</a></p>")
d('a').attr('href')#返回http://hello.com
d('p').attr('id')#返回my_id9.修改属性值,例:
d('a').attr('href', 'http://baidu.com')把href属性修改为了baidu
10.addClass(value)——为元素添加类,例:
d=pq('<div></div>')
d.addClass('my_class')#返回[<div.my_class>]11.hasClass(name)#返回判断元素是否包含给定的类,例:
d=pq("<div class='my_class'></div>")
d.hasClass('my_class')#返回True12.children(selector=None)——获取子元素,例:
d=pq("<span><p id='1'>hello</p><p id='2'>world</p></span>")
d.children()#返回[<p#1>, <p#2>]
d.children('#2')#返回[<p#2>]13.parents(selector=None)——获取父元素,例:
d=pq("<span><p id='1'>hello</p><p id='2'>world</p></span>")
d('p').parents()#返回[<span>]
d('#1').parents('span')#返回[<span>]
d('#1').parents('p')#返回[]14.clone()——返回一个节点的拷贝
15.empty()——移除节点内容
16.nextAll(selector=None)——返回后面全部的元素块,例:
d=pq("<pid='1'>hello</p><pid='2'>world</p><imgscr=''/>")
d('p:first').nextAll()#返回[<p#2>, <img>]
d('p:last').nextAll()#返回[<img>]17.not_(selector)——返回不匹配选择器的元素,例:
d=pq("<p id='1'>test 1</p><p id='2'>test 2</p>")
d('p').not_('#2')#返回[<p#1>]pyquery还有其他一些用法,这里没有一一整理出来,更多更全的方法可以直接去看它的文档。