Python爬虫之Urllib库的基本使用
# 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库的基本使用的更多相关文章
- 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是Python自带的一个用于爬虫的库,其主要作用就是可以通过代码模拟浏览器发送请求.其常被用到的子模块在Python3中的为urllib.request和urllib. ...
- python 爬虫之 urllib库
文章更新于:2020-03-02 注:代码来自老师授课用样例. 一.初识 urllib 库 在 python2.x 版本,urllib 与urllib2 是两个库,在 python3.x 版本,二者合 ...
- Python 爬虫之urllib库的使用
urllib库 urllib库是Python中一个最基本的网络请求库.可以模拟浏览器的行为,向指定的服务器发送一个请求,并可以保存服务器返回的数据. urlopen函数: 在Python3的urlli ...
- python爬虫入门urllib库的使用
urllib库的使用,非常简单. import urllib2 response = urllib2.urlopen("http://www.baidu.com") print r ...
- python爬虫之urllib库
请求库 urllib urllib主要分为几个部分 urllib.request 发送请求urllib.error 处理请求过程中出现的异常urllib.parse 处理urlurllib.robot ...
- Python爬虫系列-Urllib库详解
Urllib库详解 Python内置的Http请求库: * urllib.request 请求模块 * urllib.error 异常处理模块 * urllib.parse url解析模块 * url ...
- python爬虫03 Urllib库
Urllib 这可是 python 内置的库 在 Python 这个内置的 Urllib 库中 有这么 4 个模块 request request模块是我们用的比较多的 就是用它来发起请求 所以我 ...
随机推荐
- MySQL 索引与查询优化
本文介绍一些优化 MySQL 索引设计和查询的建议.在进行优化工作前,请务必了解MySQL EXPLAIN命令: 查看执行计划 索引 索引在逻辑上是指从索引列(关键字)到数据的映射,通过索引可以快速的 ...
- Linux文件权限与属性详解 之 一般权限
目录 一般属性 1. iNode: 3152621 2. 文件类型 3.文件访问权限 4. 链接数目: 5. 文件所有者 6. 文件所属组 7. 文件大小 8. 修改时间 9. 文件名称 Linux文 ...
- [转]玩转Angular2(4)--制作左侧自动定位菜单
本文转自:https://godbasin.github.io/2017/06/02/angular2-free-4-create-sidebar/ 因为项目原因又玩上了Angular2(v4.0+) ...
- 第一册:lesson twenty-one.
原文:Which book? A:Give me a book please,B. B:Which book? This one? A:No,not that one. The red one. B: ...
- 第一册:lesson nineteen。
原文:tired and thirsty. A:What's the matter,children? B:We are tired and thirsty. A:Sit down,here. Are ...
- 【转载】 Sqlserver中DateAdd()函数
在Sqlserver数据库中,DATEADD() 函数在日期中添加或减去指定的时间间隔.例如计算当前时间往后一天的时刻以及往前1天的时刻时间即可使用DateAdd()函数来操作,DateAdd()函数 ...
- SQL Server2008附加数据库出现错误
在用SQL Server 2008附加数据库时,出现了如下错误: 解决方法如下: 一. 检查对数据库文件及其所在文件夹是否有操作权限,右键文件属性,将权限修改为完全控制: 二. 权限改了之后,发现还是 ...
- C#与C++数据类型比较及结构体转换[整理]
//c++:HANDLE(void *) ---- c#:System.IntPtr//c++:Byte(unsigned char) ...
- git入门 创建版本库, 版本管理 分支 标签
参考: https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000 GIT最流行的分布式版本 ...
- crontab工具安装和检查
什么是crontab?crontab 是一个用于设置周期性执行任务的工具 重启crond守护进程 systemctl restart crond 查看当前crond状态 systemctl statu ...