Python网络爬虫(1)--url访问及参数设置
来源:互联网 发布:painter软件百度云 编辑:程序博客网 时间:2024/06/10 02:42
标签:
环境: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
运行代码,得到结果为
提示访问页面不存在,这个时候需要考虑一下访问方式的问题。urllib2.Request(url,data) 访问方式为POST方式,需要改用GET方式进行尝试,更改代码为
# 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
再次运行,可实现正常访问
Python网络爬虫(1)--url访问及参数设置
标签:
转载来源:http://www.mamicode.com/info-detail-477628.html
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爬虫初探——爬取网页及选择器
- SecureCRT配色方案
- 初学Intellij IDEA14配置基础svn
- CSDN网站系统升级公告
- java.io.Serializable浅析
- 机器学习2
- Python网络爬虫(1)--url访问及参数设置
- elasticsearch 配置详解
- 纯CSS画的基本图形技巧绘制(矩形、圆形、三角形、多边形、爱心、八卦等)
- android.support.v4.app.Fragment和 android.app.Fragment的区别
- Android 项目编译过程
- Android布局--Android fill_parent、wrap_content和match_parent的区别
- dlutoj(自己家的OJ的一些不错的题)
- Android中的sp和wp指针
- Objective-C编码规范(待补充)