爬虫2:urllib
一. 概述
二. urlopen用法
import urllib.request
response=urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8')
import urllib.parse
import urllib.request data=bytes(urllib.parse.urlencode({'word':'hello'}), encoding='utf8') //传入一个值
response=urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())
import urllib.request
response = urllib.request.urlopen('http://httpbin.org/get', timeout=1)
print(response.read())
import socket
import urllib.request
import urllib.error try:
response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
except urllib.error.URLError as e:
if isinstance(e.reason, socket.timeout):
print('TIME OUT')
三. 响应
import urllib.request
response = urllib.request.urlopen('https://www.python.org')
print(type(response))
import urllib.request
response = urllib.request.urlopen('https://www.python.org')
print(response.status)
print(response.getheaders()) //数组的形式,每个数组元素都是一个元组
print(response.getheader('Server')) //获取数组元素中元组键名为Server的值
import urllib.request
request = urllib.request.Request('https://python.org')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
from urllib import request,parse url = 'http://httpbin.org/post'
headers = {
'User-Agent': 'Mozilla/4.0(compatible; MSIE 5.5; Windows NT)',
'Host': 'httpbin.org'
}
dict = {
'name': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Requests(url=url, data=data, headers=headers, method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))
from urllib import request, parse url = 'http://httpdbin.org/post'
dict = {
'name': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Requests(url=url, data=data, method='POST')
req.add_header('User-Agent', 'Mozilla/4.0(compatible; MSIE 5.5; Windows NT)')
response = request.urlopen(req)
print(response.read().decode('utf-8'))
4. Handler
import urllib.request
proxy_handler = urllib.request.ProxyHander({
'http':'http://127.0.0.1:9743'
'https':'https://127.0.0.1:9743'
})
opener = urllib.requets.build_opener(proxy_handler)
response = opener.open('http://www.baidu.com')
print(response.read())
import http.cookiejar,urlib.request cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
for item in cookie:
print(item.name+"="+item.value)
import http.cookiejar, urllib.requst
filename = 'cookie.txt'
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.requst.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)
import http.cookiejar, urllib.request
filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(hander)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)
import http.cookiejar, urllib.request
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))
5. 异常处理
from urllib import request, error
try:
response = request.urlopen('http://cuiqingcai.com/index.html')
except error.URLError as e:
print(e.reason)
from urllib import request, error try:
response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e:
print(e.reason, e.code, e.headers, sep='\n')
except error,URLError as e:
print(e.reason)
else:
print('Request Successfully')
import socket
import urllib.request
import urllib.error try:
response = urllib.request.urlopen('https://www.baidu.com',timeout=0.01)
except urllib.error.URLError as e:
print(type(e.reason))
if isinstance(e.reason, socket.timeout):
print('TIME OUT')
六. URL解析
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result)
返回结果如下
<class 'urllib.parse.ParseResult'> ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')
from urllib.parse import urlparse
result = urlparse('www.baidu.com/index.html;user?id=5#comment', scheme='https')
print(result)
返回结果如下
ParseResult(scheme='https', netloc='', path='www.baidu.com/index.html', params='user', query='id=5', fragment='comment')
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', scheme='https')
print(result)
返回结果
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', allow_fragments=False)
print(result)
返回结果, 值为False时,锚点值拼接到query中
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5#comment', fragment='')
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html#comment', allow_fragments=False)
print(result)
返回结果
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html#comment', params='', query='', fragment='')
from urllib.parse import urlunparse data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']
print(urlunparse(data))
返回结果:
http://www.baidu.com/index.html;user?a=6#comment
from urllib.parse import urljoin
print(urljoin('http://www.baidu.com', 'FAQ.html'))
print(urljoin('http://www.baidu.com', 'https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html?question=2'))
print(urljoin('http://www.baidu.com?wd=abc', 'https://cuiqingcai.com/index.php'))
print(urljoin('http://www.baidu.com', '?category=2#comment'))
print(urljoin('www.baidu.com', '?category=2#comment'))
print(urljoin('www.baidu.com#comment', '?category=2'))
返回结果为
from urllib.parse import urlencode
params = {
'name': 'germey',
'age': 22
}
base_url = 'http://www.baidu.com?'
url = base_url + urlencode(params)
print(url)
爬虫2:urllib的更多相关文章
- python 3.x 爬虫基础---Urllib详解
python 3.x 爬虫基础 python 3.x 爬虫基础---http headers详解 python 3.x 爬虫基础---Urllib详解 前言 爬虫也了解了一段时间了希望在半个月的时间内 ...
- Python爬虫之urllib模块2
Python爬虫之urllib模块2 本文来自网友投稿 作者:PG-55,一个待毕业待就业的二流大学生. 看了一下上一节的反馈,有些同学认为这个没什么意义,也有的同学觉得太简单,关于Beautiful ...
- Python爬虫之urllib模块1
Python爬虫之urllib模块1 本文来自网友投稿.作者PG,一个待毕业待就业二流大学生.玄魂工作室未对该文章内容做任何改变. 因为本人一直对推理悬疑比较感兴趣,所以这次爬取的网站也是平时看一些悬 ...
- python爬虫之urllib库(三)
python爬虫之urllib库(三) urllib库 访问网页都是通过HTTP协议进行的,而HTTP协议是一种无状态的协议,即记不住来者何人.举个栗子,天猫上买东西,需要先登录天猫账号进入主页,再去 ...
- python爬虫之urllib库(二)
python爬虫之urllib库(二) urllib库 超时设置 网页长时间无法响应的,系统会判断网页超时,无法打开网页.对于爬虫而言,我们作为网页的访问者,不能一直等着服务器给我们返回错误信息,耗费 ...
- python爬虫之urllib库(一)
python爬虫之urllib库(一) urllib库 urllib库是python提供的一种用于操作URL的模块,python2中是urllib和urllib2两个库文件,python3中整合在了u ...
- python爬虫之urllib库
请求库 urllib urllib主要分为几个部分 urllib.request 发送请求urllib.error 处理请求过程中出现的异常urllib.parse 处理urlurllib.robot ...
- 练手爬虫用urllib模块获取
练手爬虫用urllib模块获取 有个人看一段python2的代码有很多错误 import re import urllib def getHtml(url): page = urllib.urlope ...
- Python爬虫之urllib.parse详解
Python爬虫之urllib.parse 转载地址 Python 中的 urllib.parse 模块提供了很多解析和组建 URL 的函数. 解析url 解析url( urlparse() ) ur ...
- 爬虫---request+++urllib
网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本.另外一些不常使用的名字还有蚂蚁.自动索引.模拟程序或者蠕 ...
随机推荐
- 【bzoj1096】仓库建设 斜率优化dp
AC通道:http://www.lydsy.com/JudgeOnline/problem.php?id=1096 [题解] 设输入的三个数组为a,b,c sumb维护b数组的前缀和,sumab维护a ...
- 【bzoj1911】[Apio2010]特别行动队
1911: [Apio2010]特别行动队 Time Limit: 4 Sec Memory Limit: 64 MBSubmit: 4048 Solved: 1913[Submit][Statu ...
- equals()方法左右变量的位置
题:一个变量,一个常量,用equals()方法比较,让咱们,看看到底是常量放前面好啊,还是变量放前面好 ------------------------------------------------ ...
- 同台机器2个网卡配置同段IP
看个例子:1.on serverifconfig eth4 192.168.1.10/24 upifconfig eth5 192.168.1.11/24 up2.on clientifconfig ...
- jquery对象的遍历$(selector).each()
<!DOCTYPE html> <html> <head> <script language="javascript" src=" ...
- 利用NotePad++ 格式化代码(格式标准化) worldsing
在阅读别人的代码时往往会遇到格式很乱,阅读起来很费劲,如果手动改很容易出错,而且很费时间,这时可以借助一些专业的编辑器来格式化代码,NotePad++是一个轻量级的代码编辑器,占用内存少,运行速度快, ...
- Electron 安装与使用
Electron是使用 JavaScript, HTML 和 CSS 构建跨平台的桌面应用 本文基于Windows进行开发的过程,记录下来,以便日后使用,Electron官网:https://elec ...
- [Android] 对ImageView设置属性scaleType为FIT_START,如何去掉多余空白
当对ImageView设置了属性scaleType为FIT_START时,可以通过调用ImageView的setAdjustViewBounds(true). 即: imageView.setScal ...
- Mysql命令行查看数据库大小(数据库版本为5.7以上)
数据库版本为5.7以上1.选择数据库use mydb1; 2.查看指定数据库表结构select * from information_schema.TABLES where information_s ...
- Linux 基础教程 32-解压缩命令
将文件压缩后对提升数据传输效率,降低传输带宽,管理备份数据都有非常重要的功能,因此文件压缩解压技能就成为必备技能.相对于Windows中的文件解压缩工具百花争艳,在Linux中的解压缩工具则要 ...