Python爬虫:urllib库的基本使用
请求网址获取网页代码
import urllib.request
url = "http://www.baidu.com"
response = urllib.request.urlopen(url)
data = response.read()
# print(data)
# 将文件获取的内容转换成字符串
str_data = data.decode("utf-8")
print(str_data)
# 将结果保存到文件中
with open("baidu.html", "w", encoding="utf-8") as f:
f.write(str_data)
get带参数请求
import urllib.request
def get_method_params(wd):
url = "http://www.baidu.com/s?wd="
# 拼接字符串
final_url = url + wd
# 发送网络请求
response = urllib.request.urlopen(final_url)
print(response.read().decode("utf-8"))
get_method_params("美女")
直接这么写会报错:

原因是,网址里面包含了汉字,但是ascii码是没有汉字的,需要转义一下:
import urllib.request
import urllib.parse
import string
def get_method_params(wd):
url = "http://www.baidu.com/s?wd="
# 拼接字符串
final_url = url + wd
# 将包含汉字的网址进行转义
encode_new_url = urllib.parse.quote(final_url, safe=string.printable)
# 发送网络请求
response = urllib.request.urlopen(encode_new_url)
print(response.read().decode("utf-8"))
get_method_params("美女")
使用字典拼接参数
import urllib.request
import urllib.parse
import string
def get_params():
url = "http://www.baidu.com/s?w"
params = {
"wd": "美女",
"key": "zhang",
"value": "san"
}
str_params = urllib.parse.urlencode(params)
print(str_params)
final_url = url + str_params
# 将带有中文的url转义
encode_url = urllib.parse.quote(final_url, safe=string.printable)
response = urllib.request.urlopen(encode_url)
data = response.read().decode("utf-8")
print(data)
get_params()
设置请求的超时时间
urlopen的参数,timeout:可以设置请求的超时时间
post请求
urllib.request.urlopen(url, data="服务器接收的数据")
User-Agent
可以伪装请求头的用户信息
常用的请求头整理:https://www.cnblogs.com/wbyixx/p/12231755.html
import urllib.request
import urllib.parse
import string
import random
def get_random_user_agent():
import random
user_agent_list = [......]
random_user_agent = random.choice(user_agent_list)
return random_user_agent
url = "http://www.baidu.com"
request = urllib.request.Request(url)
# 添加请求头信息
request.add_header("User-Agent", get_random_user_agent())
# 请求数据
response = urllib.request.urlopen(request)
# print(response.read().decode("utf-8"))
# 获取请求头信息,注意这里的agent小写
print(request.get_header("User-agent"))
handler处理器的使用
import urllib.request
def handler_openner():
# urlopen为什么可以请求数据
# 根据源码可以看出,是由于 openner,而openner又由handler而来
url = "http://www.baidu.com"
# 创建自己的处理器
handler = urllib.request.HTTPHandler()
# 创建自己的openner
openner = urllib.request.build_opener(handler)
# 用openner去请求
response = openner.open(url)
print(response.read().decode("utf-8"))
handler_openner()
添加ip代理
ip代理的分类
免费的:时效性差,错误率高
付费的:贵,也有失效不能用的
性质分类:
- 透明:对方知道我们的ip
- 匿名:对方不知道我们的真实ip,但是知道我们使用了代理
- 高匿:对方不知道我们的真实ip,也不知道我们使用了代理
使用代理ip去请求
创建 ProxyHandler
import urllib.request
def create_proxy_handler():
url = "http://www.baidu.com"
proxy = {
# 免费的写法
"http": "http://36.27.28.215:9999"
}
# 代理的处理器
proxy_handler = urllib.request.ProxyHandler(proxy)
# 创建自己的openner
openner = urllib.request.build_opener(proxy_handler)
# 拿着代理ip去发送请求
response = openner.open(url)
print(response.read().decode("utf-8"))
create_proxy_handler()
付费的代理写法:
{"http": "username:password@ip:port"}- 使用密码管理器
password_manager = urllib.request.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, proxy_uri, user, pwd)
handler_auth_proxy = urllib.request.ProxyBasicAuthHandler(password_manager)
openner_auth_proxy = urllib.request.build_opener(handler_auth_proxy)
response = openner_auth_proxy.open(url)
Cookie验证请求
手动粘贴cookie
import urllib.request
url = "需要cookie验证才能访问的链接"
headers = {
'User-Agent': 'User-Agent,Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
"Cookie": 'xxx手动粘贴cookie到这里'
}
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request)
data = response.read()
with open("data.html", "wb") as f:
f.write(data)
自动获取cookie
- 使用代码发送登录请求,获取有效的cookie
- 自动带着cookie去请求其他页面
import urllib.request
import urllib.parse
from http import cookiejar
headers = {
'User-Agent': 'User-Agent,Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
}
login_url = "..."
target_url = "https://i-beta.cnblogs.com/posts"
login_form_data = {
"username": "xxx",
"password": "xxx",
# ......其他参数
}
# 转码
login_form_data = urllib.parse(login_form_data).encode("utf-8")
# 发送请求,拿到response里的cookie
cookie_jar = cookiejar.CookieJar()
# 定义有添加cookie功能的处理器
cookie_handler = urllib.request.HTTPCookieProcessor(cookie_jar)
# 根据处理器生成openner
openner = urllib.request.build_opener(cookie_handler)
# 带着参数,发送post请求
login_request = urllib.request.Request(login_url, headers=headers, data=login_form_data)
# 如果登录成功,cookiejar会自动保存cookie
openner.open(login_request)
target_request = urllib.request.Request(target_url, headers=headers)
response = openner.open(target_request)
data = response.read()
print(data)
错误处理
常见的Error
HTTPError
UrlError
Python爬虫:urllib库的基本使用的更多相关文章
- Python爬虫Urllib库的高级用法
Python爬虫Urllib库的高级用法 设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Head ...
- Python爬虫Urllib库的基本使用
Python爬虫Urllib库的基本使用 深入理解urllib.urllib2及requests 请访问: http://www.mamicode.com/info-detail-1224080.h ...
- python爬虫 - Urllib库及cookie的使用
http://blog.csdn.net/pipisorry/article/details/47905781 lz提示一点,python3中urllib包括了py2中的urllib+urllib2. ...
- 对于python爬虫urllib库的一些理解(抽空更新)
urllib库是Python中一个最基本的网络请求库.可以模拟浏览器的行为,向指定的服务器发送一个请求,并可以保存服务器返回的数据. urlopen函数: 在Python3的urllib库中,所有和网 ...
- Python爬虫--Urllib库
Urllib库 Urllib是python内置的HTTP请求库,包括以下模块:urllib.request (请求模块).urllib.error( 异常处理模块).urllib.parse (url ...
- python爬虫---urllib库的基本用法
urllib是python自带的请求库,各种功能相比较之下也是比较完备的,urllib库包含了一下四个模块: urllib.request 请求模块 urllib.error 异常处理模块 u ...
- python爬虫 urllib库基本使用
以下内容均为python3.6.*代码 学习爬虫,首先有学会使用urllib库,这个库可以方便的使我们解析网页的内容,本篇讲一下它的基本用法 解析网页 #导入urllib from urllib im ...
- Python爬虫urllib库的使用
urllib 在Python2中,有urllib和urllib2两个库实现请求发送,在Python3中,统一为urllib,是Python内置的HTTP请求库 request:最基本的HTTP请求模块 ...
- Python爬虫 Urllib库的高级用法
1.设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Headers 的属性. 首先,打开我们的浏览 ...
- python爬虫urllib库使用
urllib包括以下四个模块: 1.request:基本的HTTP请求模块,可以用来模拟发送请求.就像在浏览器里输入网址然后回车一样,只需要给库方法传入URL以及额外的参数,就可以模拟实现这个过程. ...
随机推荐
- AcWing 900. 整数划分
#include <iostream> #include <algorithm> using namespace std; , mod = 1e9 + ; int n; int ...
- 1.6 SQL (根据时间取值)
select * from 表名 where createdate > date_add(subdate(curdate(),date_format(curdate(),'%w')-1),int ...
- 【游戏体验】Sift Heads World Act 1(暗杀行动1)
>>>点此处可试玩无敌版<<< 注意,本游戏含有少量暴力元素,13岁以下的儿童切勿尝试本款游戏 非常良心的火柴人游戏,值得一玩 个人测评 游戏性 8/10 音乐 9 ...
- HTML学习(5)标题、水平线、注释
HTML 标题 标题(Heading)是通过 <h1> - <h6> 标签进行定义的. <h1> 定义最大的标题. <h6> 定义最小的标题. 注: 浏 ...
- [IOI2005]河流
Description Luogu3354 Solution 一道树形dp的题. 首先考虑转移,很简单,就是这个点做不做伐木场.为了方便转移,我们定义状态为\(f_{i,j,k}\)表示点\(i\)及 ...
- linux中systemctl详细理解及常用命令
linux中systemctl详细理解及常用命令 https://blog.csdn.net/skh2015java/article/details/94012643 一.systemctl理解 Li ...
- Makefile的编写及四个特殊符号的意义@、$@、$^、$
https://www.cnblogs.com/sky-heaven/p/9450435.html Makefile一般的格式是: target:components rule 一.@ 这个符串通常用 ...
- 【vue store的使用方法】(this.$store.state this.$store.getters this.$store.dispatch this.$store.commit)
vue 页面文件 <template> <div> {{this.$store.state.count}}<br/> {{count}}<br/> {{ ...
- docker容器 - 进入容器、删除容器
实验环境 CentOS 7.5 容器 容器是镜像的运行实例.不同的是,镜像是静态的只读文件,而容器带有运行时需要的可写文件层:同时,容器中的应用进程处于运行状态. 进入容器 可使用以下命令进入容器: ...
- Vue 实现todolist的添加删除功能
直接上代码 vm.$emit( eventName, [-args] ) 触发当前实例上的事件 可选附加参数 传给监听器回调. <style> #app{ margin: 100px; } ...