Python学习网络爬虫主要分3个大的版块:抓取,分析,存储
html结构,请求,解析,存储
python与R爬虫
URL请求过程
当访问一个网站如‘https://zhuanlan.zhihu.com/’时会发生什么?简单来说这段过程发生了以下四个步骤:
1. 查找域名对应的IP地址。
2. 向IP对应的服务器发送请求。
3. 服务器响应请求,发回网页内容。
4. 浏览器解析网页内容。
网络爬虫要做的就是实现浏览器的功能。通过指定url,直接返回给用户所需要的数据,而不需要一步步人工去操纵浏览器获取。
抓取这一步,你要明确要得到的内容是什么?
是HTML源码,还是Json格式的字符串等。
- [x] 最基本的抓取抓取大多数情况属于get请求,即直接从对方服务器上获取数据。
首先,Python中自带urllib及urllib2这两个模块,基本上能满足一般的页面抓取。另外,requests也是非常有用的包,与此类似的,还有httplib2等等。
Requests:
import requests
response = requests.get(url)
content = requests.get(url).content
print "response headers:", response.headers
print "content:", content
Urllib2:
import urllib2
response = urllib2.urlopen(url)
content = urllib2.urlopen(url).read()
print "response headers:", response.headers
print "content:", content
Httplib2:
import httplib2
http = httplib2.Http()
response_headers, content = http.request(url, 'GET')
print "response headers:", response_headers
print "content:", content
此外,对于带有查询字段的url,get请求一般会将来请求的数据附在url之后,以?分割url和传输数据,多个参数用&连接。
data = {'data1':'XXXXX