# get请求
import urllib.request
response = urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode('utf-8')) # post请求
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('http://www.python.org')
print(type(response)) # 状态码、响应头
import urllib.request
response = urllib.request.urlopen('http://www.python.org')
print(response.status)
print(response.getheaders())
print(response.getheader('server')) # Request
import urllib.request
request = urllib.request.Request('http://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': 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',
'Host':'httpbin.org'
}
dict = {
'name':'Germey'
}
data = bytes(parse.urlencode(dict), encoding = 'utf-8')
req = request.Request(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://httpbin.org/post'
dict = {
'name': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding = 'utf-8')
req = request.Request(url = url, data = data, method = 'POST')
req.add_header('User-Agent', 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36')
response = request.urlopen(req)
print(response.read().decode('utf-8')) #代理
import urllib.request
proxy_handler = urllib.request.ProxyHandler({
'http': 'http://127.0.0.1:9743',
'https': 'https://127.0.0.1:9743'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('http://httpbon.org/get')
print(response.read()) # cookie
import http.cookiejar, urllib.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) # 保存cookie为1.txt
import http.cookiejar, urllib.request
filename = '1.txt'
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard = True, ignore_expires = True) # 另外一种方式保存cookie
import http.cookiejar, urllib.request
filename = '1.txt'
cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard = True, ignore_expires = True) # 读取cookie
import http.cookiejar, urllib.request
cookie = http.cookiejar.LWPCookieJar()
cookie.load('1.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')) # 异常处理
from urllib import request, error
try:
response = request.urlopen('http://lidonghao.com')
except error.URLError as e:
print(e.reason) from urllib import request, error
try:
response = request.urlopen('http://www.baidu.com/101')
except error.HTTPError as e:
print(e.reason, e.code, 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
# urlparse
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result) from urllib.parse import urlparse
result = urlparse('www.baidu.com/index.html;user?id=5#comment', scheme = "https")
print(result) from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', scheme = "https")
print(result) from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', allow_fragments = False)
print(result) from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html#comment', allow_fragments = False)
print(result)
 # urlunparse
from urllib.parse import urlunparse
data = ['http', 'www.baidu.com', 'index,html', 'user', 'a=6', 'comment']
print(urlunparse(data)) # urljoin
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', 'http://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')) # urlencode
from urllib.parse import urlencode
params = {
'name':'germey',
'age':22
}
base_url = 'http://www.baidu.com'
url = base_url + urlencode(params)
print(url)

Python爬虫之Urllib库的基本使用的更多相关文章

  1. python爬虫之urllib库(三)

    python爬虫之urllib库(三) urllib库 访问网页都是通过HTTP协议进行的,而HTTP协议是一种无状态的协议,即记不住来者何人.举个栗子,天猫上买东西,需要先登录天猫账号进入主页,再去 ...

  2. python爬虫之urllib库(二)

    python爬虫之urllib库(二) urllib库 超时设置 网页长时间无法响应的,系统会判断网页超时,无法打开网页.对于爬虫而言,我们作为网页的访问者,不能一直等着服务器给我们返回错误信息,耗费 ...

  3. python爬虫之urllib库(一)

    python爬虫之urllib库(一) urllib库 urllib库是python提供的一种用于操作URL的模块,python2中是urllib和urllib2两个库文件,python3中整合在了u ...

  4. python爬虫之urllib库介绍

    一.urllib库 urllib是Python自带的一个用于爬虫的库,其主要作用就是可以通过代码模拟浏览器发送请求.其常被用到的子模块在Python3中的为urllib.request和urllib. ...

  5. python 爬虫之 urllib库

    文章更新于:2020-03-02 注:代码来自老师授课用样例. 一.初识 urllib 库 在 python2.x 版本,urllib 与urllib2 是两个库,在 python3.x 版本,二者合 ...

  6. Python 爬虫之urllib库的使用

    urllib库 urllib库是Python中一个最基本的网络请求库.可以模拟浏览器的行为,向指定的服务器发送一个请求,并可以保存服务器返回的数据. urlopen函数: 在Python3的urlli ...

  7. python爬虫入门urllib库的使用

    urllib库的使用,非常简单. import urllib2 response = urllib2.urlopen("http://www.baidu.com") print r ...

  8. python爬虫之urllib库

    请求库 urllib urllib主要分为几个部分 urllib.request 发送请求urllib.error 处理请求过程中出现的异常urllib.parse 处理urlurllib.robot ...

  9. Python爬虫系列-Urllib库详解

    Urllib库详解 Python内置的Http请求库: * urllib.request 请求模块 * urllib.error 异常处理模块 * urllib.parse url解析模块 * url ...

  10. python爬虫03 Urllib库

    Urllib   这可是 python 内置的库 在 Python 这个内置的 Urllib 库中 有这么 4 个模块 request request模块是我们用的比较多的 就是用它来发起请求 所以我 ...

随机推荐

  1. Python numpy中矩阵的用法总结

    关于Python Numpy库基础知识请参考博文:https://www.cnblogs.com/wj-1314/p/9722794.html Python矩阵的基本用法 mat()函数将目标数据的类 ...

  2. MySQL中字段字符集不同导致索引不能命中

    今天写了一个sql,其中涉及的表中的数据量都差不多为50w左右,查询发现用了8s.这个只是测试服上数据,放到正式服上,肯定一运行就挂了. SELECT Orders. NO, GuidNo, Orde ...

  3. java开发各层对象含义

    综述 java的几种对象(PO,VO,DAO,BO,POJO)解释: 一.PO:persistant object 持久对象,可以看成是与数据库中的表相映射的java对象.最简单的PO就是对应数据库中 ...

  4. Python网络编程Socket之协程

    一.服务端 __author__ = "Jent Zhang" import socket import gevent from gevent import monkey monk ...

  5. mybatis_05动态SQL_if和where

    If标签:作为判断入参来使用的,如果符合条件,则把if标签体内的SQL拼接上. 注意:用if进行判断是否为空时,不仅要判断null,也要判断空字符串‘’: Where标签:会去掉条件中的第一个and符 ...

  6. Netty实战十二之WebSocket

    如果你有跟进Web技术的最新进展,你很可能就遇到过“实时Web”这个短语,这里并不是指所谓的硬实时服务质量(QoS),硬实时服务质量是保证计算结果将在指定的时间间隔内被递交.仅HTTP的请求/响应模式 ...

  7. C#设计模式之六适配器模式(Adapter Pattern)【结构型】

    一.引言 从今天开始我们开始讲[结构型]设计模式,[结构型]设计模式有如下几种:适配器模式.桥接模式.装饰模式.组合模式.外观模式.享元模式.代理模式.[创建型]的设计模式解决的是对象创建的问题,那[ ...

  8. 如何用STAR法则来回答「宝洁八大问」

    掌握宝洁八大问,其实就是掌握了半个求职季 每年高峰期,很多同学会问到关于宝洁八大的问题,如何准备.怎么讲故事.如何体现自己的特点等等.针对同学们的提问,分享一篇关于如何回答好宝洁八大问的文章,希望能够 ...

  9. 玩游戏 学Flex布局

    大家好,今天推荐一个学习Flex布局的网页小游戏,非常不错,是国外的牛人开发的,值得一试,重复几次,就会大概了解Flex的属性了! 地址: http://flexboxfroggy.com/#zh-c ...

  10. es6 语法 (数值扩展)

    { //二进制数值都是0b开头,八进制0o console.log(0b111110111) console.log(0o767); } { console.log('15',Number.isFin ...