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,效果如下:
可以看到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")得到结果为
提示访问页面不存在,这个时候需要考虑一下访问方式的问题。使用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
再次运行,获得结果为
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
再次运行,可实现正常访问
http://leettest.com/blog/
0 0
- Python网络爬虫(1)--url访问及参数设置
- Python网络爬虫(1)--url访问及参数设置
- Python网络爬虫的学习(1)URI与URL
- Python网络爬虫(1)
- python 网页爬虫(URL)
- [Python]网络爬虫1
- Python网络爬虫1
- 【网络爬虫】【python】网络爬虫(一):python爬虫概述
- [Python]网络爬虫(八):糗事百科的网络爬虫(v0.2)源码及解析
- [Python]网络爬虫(八):糗事百科的网络爬虫(v0.2)源码及解析
- [Python]网络爬虫:糗事百科的网络爬虫(v0.2)源码及解析
- [Python]网络爬虫:百度贴吧的网络爬虫(v0.4)源码及解析
- python网络爬虫——基本概念及代码实现1
- Python网络爬虫(五)-----geturl及info
- Python网络爬虫(1)获取网页
- python网络爬虫(1)--抓取图片
- 网络访问 URL,HttpURLConnection及 HttpClient:
- 【网络爬虫】【python】网络爬虫(五):scrapy爬虫初探——爬取网页及选择器
- C++第一次实验-1
- (七) Freemarker 发送邮件
- 使用C++实现OO观察者模式
- windows 2003 配置多个tomcat需注意的配置点
- 读书笔记-《Linux/Unix设计思想》
- Python网络爬虫(1)--url访问及参数设置
- 读书笔记-《Java核心技术卷I-基础知识》
- ORACLE中 %TYPE 和 %ROWTYPE 的使用
- Robot Framework 教程 (1) - 环境配置及简单网站兼容性测试
- mysql修改数据库表和表中的字段的编码格式的修改
- Robot Framework 教程 (2) - 页面元素定位
- Robot Framework 教程 (3) - Resource及关键字 的使用
- (八) Freemarker 总结
- Robot Framework 教程 (4) - 自定义Library