# 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. SpringCloud(1) 架构演进和基础知识简介

    一.传统架构演进到分布式架构 简介:讲解单机应用和分布式应用架构演进基础知识 (画图) 高可用 LVS+keepalive 1.单体应用:开发速度慢.启动时间长.依赖庞大.等等 2.微服务:易开发.理 ...

  2. vue+vue-router+vuex实战

    shopping vue + vue-router + vuex实现电商网站 效果展示 install 下载代码: git clone https://github.com/chenchangyuan ...

  3. Perl的输出:print、say和printf、sprintf

    print.printf和say都可以输出信息.print和say类似,print不自带换行符,say自带换行符,但要使用say,必须写use语句use 5.010;,printf像C语言的print ...

  4. Go基础系列:空接口

    空接口 空接口是指没有定义任何接口方法的接口.没有定义任何接口方法,意味着Go中的任意对象都可以实现空接口(因为没方法需要实现),任意对象都可以保存到空接口实例变量中. 空接口的定义方式: type ...

  5. Qt 编程中 namespace Ui { class Widget; } 解析

    class Widget 里面有个声明 Ui::Widget *ui,这个 ui 是使用 namespace Ui 里的 Widget 类声明的,该类只是简单的继承了 ui_widget.h 里的 U ...

  6. μC/OS-II 要点分析 ------ PendSV_Handler

    首先贴出今天要与大家分享的内容源码(位于内核源码的 os_cpu_a.asm 中): PendSV_Handler CPSID I MRS R0, PSP CBZ R0, PendSV_Handler ...

  7. 【转载】C#生成图片的缩略图

    图片处理是C#程序开发中时常会涉及到的一个业务,除了图像的上传.保存以及下载等功能外,根据上传的图片生成一个缩略图也是常见业务,在C#语言中,可以通过Image类提供的相关方法对图片进行操作,如指定宽 ...

  8. C#基础知识总结(二)

    摘要 第二篇主要讲:变量.连接符占位符等.转义字符.数据的计算.数据的转换.try-catch的简单熟悉.复合运算符和自加自减 一.变量 1.数据存储在内存中:内存叫做RAM,内存被分隔为一小格一小格 ...

  9. js中const,var,let区别(转载)

    js中const,var,let区别 来源:https://www.cnblogs.com/zzsdream/p/6372729.html 今天第一次遇到const定义的变量,查阅了相关资料整理了这篇 ...

  10. IE console.log 调试状态

    最近项目遇到问题,发现alert一个弹窗,在IE中,打开开发人员工具后,可以弹出,但是不打开无法弹出,最后发现是console.log的原因,注释掉console相关的代码,问题就解决了 有些版本的I ...