如之前的几篇文章《Python爬虫框架之Scrapy详解》、《Python爬虫框架Scrapy之爬取糗事百科大量段子数据)》,使用了Scrapy框架并且爬取了糗事百科的段子存入MongoDB中。
Scrapy框架很好,也提供了很多扩展点,可以自己编写中间件处理Scrapy的Request和Response。但是可定制化或者可掌控性来说,还是自己写的爬虫更加强一些。
如果写简单更加可控的爬虫,还是建议使用Python第三方库:requests和bs4。
requests和bs4爬空姐网图片
requests库
requests是Python非常流行的处理网络数据的第三方库。相对于Python内置框架urllib、urllib2来说,requests提供的操作更加简洁而且更加丰富。如requests示例:
#HTTP请求类型
#get类型
r = requests.get('https://github.com/timeline.json')
#post类型
r = requests.post("http://m.ctrip.com/post")
#put类型
r = requests.put("http://m.ctrip.com/put")
#delete类型
r = requests.delete("http://m.ctrip.com/delete")
#head类型
r = requests.head("http://m.ctrip.com/head")
#options类型
r = requests.options("http://m.ctrip.com/get")
#获取响应内容
print r.content #以字节的方式去显示,中文显示为字符
print r.text #以文本的方式去显示
#URL传递参数
payload = {
'keyword': '日本', 'salecityid': '2'}
r = requests.get("http://m.ctrip.com/webapp/tourvisa/visa_list", params=payload)
print r.url #示例为http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid=2&keyword=日本
#获取/修改网页编码
r = requests.get('https://github.com/timeline.json')
print r.encoding
r.encoding = 'utf-8'
#json处理
r = requests.get('https://github.com/timeline.json')
print r.json() #需要先import json
#定制请求头
url = 'http://m.ctrip.com'
headers = {
'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'}
r = requests.post(url, headers=headers)
print r.