爬虫基础(1):urllib库

urllib库

urllib库是python中的一个基本网络请求库。用于模拟浏览器的行为,向指定服务器发送请求,并接收返回的数据。

在python3中所有的网络请求相关函数都集中在urllib.request模块下面

urlopen函数

向服务器发起请求

urlopen函数的参数

  1. url 目标地址
  2. data 如果有这个参数,将变为post请求
  3. 返回值 http.client.HTTPResponse对象,其中含有下面几个方法:
    • read(size) size为空则读取所有
    • readline() 读取一行
    • readlines() 读取多行
    • getcode() 读取状态值
      基本的使用:
    from urllib import request
    res = request.urlopen("http://www.baidu.com")
    print(res.read())

urlretrieve函数

这个函数可以方便的将网页的一个文件保存到本地。

urlretrieve函数的参数

  1. url 目标地址
  2. 下载路径
    基本使用
from urllib import request
request.urlretrieve("http://www.baidu.com","index.html") #下载百度首页到index.html

urlencode函数

用于完成url中中文以及特殊字符的编码和解码

基本使用:

from urllib import parse
params = {
    "name": "张三",
    "age": 14,
    "地址": "上海市海河大道1544弄3号楼302"
}
res = parse.urlencode(params)
print(res)

执行结果:
age=14&name=%E5%BC%A0%E4%B8%89&%E5%9C%B0%E5%9D%80=%E4%B8%8A%E6%B5%B7%E5%B8%82%E6%B5%B7%E6%B2%B3%E5%A4%A7%E9%81%931544%E5%BC%843%E5%8F%B7%E6%A5%BC302

在百度上搜索刘德华

from urllib import request
from urllib import parse

# request.urlopen("http://www.baidu.com/s/?wd=刘德华") #直接这样请求会报错
url = "http://www.baidu.com/s/?"
# 定义参数字典
params = {
    "wd": "刘德华"
}
# 参数转码
qs = parse.urlencode(params)
# url拼接
url += qs
# 发送请求
res = request.urlopen(url)
print(res.read())

parse_qs函数

将已经编码的url进行解码
基本使用

from urllib import parse
qs = "age=14&name=%E5%BC%A0%E4%B8%89&%E5%9C%B0%E5%9D%80=%E4%B8%8A%E6%B5%B7%E5%B8%82%E6%B5%B7%E6%B2%B3%E5%A4%A7%E9%81%931544%E5%BC%843%E5%8F%B7%E6%A5%BC302"
res = parse.parse_qs(qs)
print(res)

执行结果
{‘name‘: [‘张三‘], ‘age‘: [‘14‘], ‘地址‘: [‘上海市海河大道1544弄3号楼302‘]}

urlparse 和 urlsplit函数

用于将url各个部分进行分割

基本使用

from urllib import parse
url = "http://www.baidu.com/s/?wd=python"

res = parse.urlsplit(url)
print(res)
res = parse.urlparse(url)
print(res)

执行结果:
SplitResult(scheme=‘http‘, netloc=‘www.baidu.com‘, path=‘/s/‘, query=‘wd=python‘, fragment=‘‘)
ParseResult(scheme=‘http‘, netloc=‘www.baidu.com‘, path=‘/s/‘, params=‘‘, query=‘wd=python‘, fragment=‘‘)

可以发现两个结果基本相同,唯一不同的是urlsplit()函数返回结果没有params属性

request.Request类

如果需要在请求中添加header信息,则必须用request.Request类实现
基本使用:

# 通过构造请求头 获取拉勾网的招聘信息
from urllib import request
from urllib import parse
url = "https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false"

headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
    'Referer': 'https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=',
    "Cookie": "_ga=GA1.2.620765502.1560083999; _gid=GA1.2.758158058.1560083999; user_trace_token=20190609203959-b18d608c-8ab3-11e9-a228-5254005c3644; LGUID=20190609203959-b18d64d3-8ab3-11e9-a228-5254005c3644; index_location_city=%E5%85%A8%E5%9B%BD; JSESSIONID=ABAAABAAAIAACBI2C1935D6770E19BC5BE4390354414026; X_HTTP_TOKEN=b6c2ab256a325419948821065120ec66a55a5e4b49; _gat=1; LGSID=20190610090729-1e5547bf-8b1c-11e9-a22c-5254005c3644; PRE_UTM=; PRE_HOST=; PRE_SITE=; PRE_LAND=https%3A%2F%2Fwww.lagou.com%2F; LGRID=20190610090729-1e5549e6-8b1c-11e9-a22c-5254005c3644; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1560084000,1560090525,1560128850; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1560128850; TG-TRACK-CODE=index_search; SEARCH_ID=60cd24c737344a6f98c48dd4fc94c39c"
}

data = {
    "first": "true",
    "pn": 1,
    "kd": "python"
}

req = request.Request(url, headers=headers, data=(
    parse.urlencode(data)).encode("utf-8"), method="POST")
resp = request.urlopen(req)
print(resp.read().decode("utf-8"))

原文地址:https://www.cnblogs.com/asia9847/p/10996332.html

时间: 2024-08-17 14:08:54

爬虫基础(1):urllib库的相关文章

爬虫基础之urllib库

categories: 爬虫 tags: urlopen urlretrieve urlencode parse_qs urlparse urlsplit urllib库 urllib库是Python中一个最基本的网络请求库.可以模拟浏览器的行为,向指定的服务器发送一个请求,并可以保存服务器返回的数据 urlopen函数 在Python3的urllib库中,所有和网络请求相关的方法,都被集到 urllib.request 模块下面了,先来看下urlopen的基本使用 from urllib im

第三百三十节,web爬虫讲解2—urllib库爬虫—实战爬取搜狗微信公众号

第三百三十节,web爬虫讲解2-urllib库爬虫-实战爬取搜狗微信公众号 封装模块 #!/usr/bin/env python # -*- coding: utf-8 -*- import urllib from urllib import request import json import random import re import urllib.error def hq_html(hq_url): """ hq_html()封装的爬虫函数,自动启用了用户代理和ip

Python3网络爬虫——二、Urllib库的基本使用

一.什么是Urllib Urllib库是Python自带的一个http请求库,包含以下几个模块: urllib.request 请求模块 urllib.error   异常处理模块 urllib.parse   url解析模块 urllib.robotparser  robots.txt解析模块 其中前三个模块比较常用,第四个仅作了解. 二.Urllib方法介绍 将结合Urllib的官方文档进行说明.首先是urllib.request模块: urllib.request.urlopen(url,

Python爬虫入门之Urllib库的高级用法

1.设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Headers 的属性. 首先,打开我们的浏览器,调试浏览器F12,我用的是Chrome,打开网络监听,示意如下,比如知乎,点登录之后,我们会发现登陆之后界面都变化了,出现一个新的界面,实质上这个页面包含了许许多多的内容,这些内容也不是一次性就加载完成的,实质上是执行了好多次请求,一般是首先请求HTML文件,然后加载JS,CSS 等等,经过多次

爬虫常用的 urllib 库知识点

urllib 库 urllib 库是 Python 中一个最基本的网络请求库.它可以模仿浏览器的行为向指定的服务器发送请求,同时可以保存服务器返回的数据. urlopen() 在 Python3 的 urllib 库中,所有和网络请求的相关方法都被集中到 urllib.request 模块下了.以下是 urlopen() 方法最基本的使用方法: from urllib import request resp = request.urlopen('https://www.baidu.com') p

爬虫(二):urllib库文件的基础和进阶(python2.7)

1 import urllib2 2 url="https//www.baidu.com"; 3 response=urllib2.urlopen(url); 4 print response.read()5 #************************************同样上面网页的代码可以通过request对象进行访问************ request=urllib2.Request(url) response=urllib2.urlopen(request) p

Python爬虫入门之三urllib库的基本使用

前言 所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地.在Python中有很多库可以用来抓取网页,我们先学习urllib. 注:此博客开发环境为python3 urlopen 我们先来段代码: # urllib_urlopen.py # 导入urllib.request import urllib.request # 向指定的url发送请求,并返回服务器响应的类文件对象 response = urllib.request.urlopen("http://www.bai

python爬虫二、Urllib库的基本使用

什么是Urllib Urllib是python内置的HTTP请求库 包括以下模块 urllib.request 请求模块 urllib.error 异常处理模块 urllib.parse url解析模块 urllib.robotparser robots.txt解析模块 urlopen 关于urllib.request.urlopen参数的介绍: urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=No

九 web爬虫讲解2—urllib库爬虫—实战爬取搜狗微信公众号—抓包软件安装Fiddler4讲解

封装模块 #!/usr/bin/env python # -*- coding: utf-8 -*- import urllib from urllib import request import json import random import re import urllib.error def hq_html(hq_url): """ hq_html()封装的爬虫函数,自动启用了用户代理和ip代理 接收一个参数url,要爬取页面的url,返回html源码 "