Python网络爬虫(1)--url访问及参数设置

来源:互联网 发布:淘宝上买黄牛票犯法吗 编辑:程序博客网 时间:2024/05/18 22:40
环境:Python2.7.9 / Sublime Text 2 / Chrome

1.url访问,直接调用urllib库函数即可

import urllib2url='http://www.baidu.com/'response = urllib2.urlopen(url)html=response.read()print html

2.带参数的访问,以baidu搜索功能为例

使用Chrome浏览器访问效果,Chrome搜索引擎设置为baidu,地址栏中输入test,效果如下:

image

可以看到baidu搜索的url为 https://www.baidu.com/s?ie=UTF-8&wd=test

修改代码,增加访问参数

# coding=utf-8import urllibimport urllib2#url地址url='https://www.baidu.com/s'#参数values={        'ie':'UTF-8',        'wd':'test'           }#进行参数封装data=urllib.urlencode(values)#组装完整urlreq=urllib2.Request(url,data)#访问完整urlresponse = urllib2.urlopen(req)html=response.read()print html

运行代码,(Sublime Text 如果出现Decode error,需要将Python.sublime-build设置为"encoding": "utf-8")得到结果为

image

提示访问页面不存在,这个时候需要考虑一下访问方式的问题。使用Chrome开发者工具,监测Network,确定访问方式为GET

 

urllib2.Request(url,data) 访问方式为POST方式,改用GET方式进行尝试,需要手动组装URL,更改代码为

# coding=utf-8import urllibimport urllib2#url地址url='https://www.baidu.com/s'#参数values={        'ie':'UTF-8',        'wd':'test'           }#进行参数封装data=urllib.urlencode(values)#组装完整url#req=urllib2.Request(url,data)url=url+'?'+data#访问完整url#response = urllib2.urlopen(req)response = urllib2.urlopen(url)html=response.read()print html

再次运行,获得结果为

image

https发生了重定向,需要改用http

# coding=utf-8import urllibimport urllib2#url地址#url='https://www.baidu.com/s'url='http://www.baidu.com/s'#参数values={        'ie':'UTF-8',        'wd':'test'           }#进行参数封装data=urllib.urlencode(values)#组装完整url#req=urllib2.Request(url,data)url=url+'?'+data#访问完整url#response = urllib2.urlopen(req)response = urllib2.urlopen(url)html=response.read()print html

再次运行,可实现正常访问

image

 

http://leettest.com/blog/

 

0 0
原创粉丝点击