Python爬虫:urllib内置库基本使用

简介: Python爬虫:urllib内置库基本使用

可参考:


Urllib库的基本使用


官方文档:https://docs.python.org/3/library/urllib.html


urllib库包含以下模块
urllib.request 请求模块
urllib.error 异常处理模块
urllib.parse url解析模块
urllib.robotparser robots.txt解析模块

py2 vs. py3

python2
urllib.urlopen()
python3
urllin.request.urlopen()

用于http测试的网站:http://httpbin.org/


引入需要的模块

from urllib import request
from urllib import parse
from urllib import error
from http import cookiejar
import socket

request请求

请求url,请求参数, 请求数据, 请求头


urlopen
urlopen(url, data=None, timeout, *, cafile=None, 
    capath=None, cadefault=False, context=None)


# 发送get请求
def foo1():
    response = request.urlopen("http://www.baidu.com")
    # 字节 -> utf-8解码 -> 字符串
    print(response.read().decode("utf-8"))
# 发送post请求
def foo2():
    data = bytes(parse.urlencode({"word": "hello"}), encoding="utf-8")
    response = request.urlopen("http://httpbin.org/post", data=data)
    print(response.read())
# 设置超时时间并捕获异常
def foo3():
    try:
        response = request.urlopen("http://httpbin.org/post", timeout=0.1)
        print(response.read())
    except error.URLError as e:
        print(type(e.reason)) # <class 'socket.timeout'>
        if isinstance(e.reason, socket.timeout):
            print("超时错误:", e)

response响应


# 状态码,响应头
def foo4():
    response = request.urlopen("http://www.baidu.com")
    print(type(response))
    # from http.client import HTTPResponse
    # <class 'http.client.HTTPResponse'>
    print(response.status)
    print(response.getheaders())
    print(response.getheader("Server"))

Request请求对象

def foo5():
    req = request.Request("http://www.baidu.com")
    response = request.urlopen(req)
    print(response.read().decode("utf-8"))
# 带浏览器信息的请求1
def foo6():
    url = "http://httpbin.org/post"
    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)",
        "Host": "httpbin.org"
    }
    dct = {"name": "Tom"}
    data = bytes(parse.urlencode(dct), encoding="utf-8")
    req = request.Request(url=url, data=data, headers=headers)
    response = request.urlopen(req)
    print(response.read().decode("utf-8"))
# 带浏览器信息的请求2
def foo7():
    url = "http://httpbin.org/post"
    dct = {"name": "Tom"}
    data = bytes(parse.urlencode(dct), encoding="utf-8")
    req = request.Request(url=url, data=data, method="POST")
    req.add_header("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)")
    response = request.urlopen(req)
    print(response.read().decode("utf-8"))

代理


def foo8():
    proxy_handler = request.ProxyHandler({
        "http": "http://183.159.94.185:18118",
        "https": "https://183.159.94.187:18118",
        })
    opener = request.build_opener(proxy_handler)
    response = opener.open("http://www.baidu.com")
    print(response.read())

cookie


def foo9():
    cookie = cookiejar.CookieJar()
    cookie_handler = request.HTTPCookieProcessor(cookie)
    opener = request.build_opener(cookie_handler)
    response = opener.open("http://www.baidu.com")
    print(response.status)
    for item in cookie:
        print(item.name, item.value)
# 保存cookie1
def foo10():
    filename = "cookie.txt"
    cookie = cookiejar.MozillaCookieJar(filename)
    cookie_handler = request.HTTPCookieProcessor(cookie)
    opener = request.build_opener(cookie_handler)
    response = opener.open("http://www.baidu.com")
    cookie.save(ignore_discard=True, ignore_expires=True)
# 保存cookie2
def foo11():
    filename = "cookie1.txt"
    cookie = cookiejar.LWPCookieJar(filename)
    cookie_handler = request.HTTPCookieProcessor(cookie)
    opener = request.build_opener(cookie_handler)
    response = opener.open("http://www.baidu.com")
    cookie.save(ignore_discard=True, ignore_expires=True)
# 读取cookie
def foo12():
    filename = "cookie1.txt"
    cookie = cookiejar.LWPCookieJar()
    cookie.load(filename, ignore_discard=True, ignore_expires=True)
    cookie_handler = request.HTTPCookieProcessor(cookie)
    opener = request.build_opener(cookie_handler)
    response = opener.open("http://www.baidu.com")
    print(response.read().decode("utf-8"))

异常处理

error主要有:’URLError’, ‘HTTPError’, ‘ContentTooShortError’



def foo13():
    try:
        response = request.urlopen("http://www.xxooxxooxox.com/xxx")
        print(response.status)
    except error.HTTPError as e:  # 子类异常
        print(e.name, e.reason, e.code, e.headers, sep="\n")
    except error.URLError as e:  # 父类异常
        print(e.reason)
    else:
        print("successful")

parse 模块解析url

urlparse(url, scheme='', allow_fragments=True)


def foo14():
    result = parse.urlparse("http://www.baidu.com/xxx.html;user?id=5#comment")
    print(type(result), result, sep="\n")
    """
    <class 'urllib.parse.ParseResult'>
    ParseResult(scheme='http', netloc='www.baidu.com', path='/xxx.html', 
            params='user', query='id=5', fragment='comment')
    """
    # scheme 为默认协议信息 链接中协议信息优先
    result = parse.urlparse("www.baidu.com", scheme="https")
    print(result)
    """
    ParseResult(scheme='https', netloc='', path='www.baidu.com',
          params='', query='', fragment='')
    """
    result = parse.urlparse("http://www.baidu.com", scheme="https")
    print(result)
    """
    ParseResult(scheme='http', netloc='www.baidu.com', path='', 
            params='', query='', fragment='')
    """
    # allow_fragments 参数决定锚点拼接的位置
    result = parse.urlparse("http://www.baidu.com/xxx.html;user?id=5#comment",
                    allow_fragments=True)
    print(result)
    """
    ParseResult(scheme='http', netloc='www.baidu.com', path='/xxx.html', 
            params='user', query='id=5', fragment='comment')
    """
    result = parse.urlparse("http://www.baidu.com/xxx.html;user?id=5#comment",
                    allow_fragments=False)
    print(result)
    """
    ParseResult(scheme='http', netloc='www.baidu.com', path='/xxx.html', 
            params='user', query='id=5#comment', fragment='')
    """
    result = parse.urlparse("http://www.baidu.com/xxx.html;user#comment",
                    allow_fragments=False)
    print(result)
    """
    ParseResult(scheme='http', netloc='www.baidu.com', path='/xxx.html', 
            params='user#comment', query='', fragment='')
    """
# urlunparse 拼接url链接,注意顺序
def foo15():
    data = ["http", "www.baidu.com", "index.html", "user", "a=6", "comment"]
    print(parse.urlunparse(data))
    # http://www.baidu.com/index.html;user?a=6#comment
# urljoin 拼接url,类似os.path.join, 后者优先级高
def foo16():
    print(parse.urljoin("http://www.baidu.com", "index.html"))
    print(parse.urljoin("http://www.baidu.com", "http://www.qq.com/index.html"))
    print(parse.urljoin("http://www.baidu.com/index.html", "http://www.qq.com/?id=6"))
    """
   http://www.baidu.com/index.html
   http://www.qq.com/index.html
   http://www.qq.com/?id=6
    """
# urlencode将字典转为url中的参数形式
def foo17():
    params ={
        "name": "Tom",
        "age": 18
    }
    # 这里 ? 没了
    url = parse.urljoin("http://www.baidu.com/?", parse.urlencode(params))
    print(url)
    # http://www.baidu.com/name=Tom&age=18
    url = "http://www.baidu.com/?" + parse.urlencode(params)
    print(url)
    # http://www.baidu.com/?name=Tom&age=18

相关文章
|
1天前
|
数据采集 存储 数据挖掘
深入探索 Python 爬虫:高级技术与实战应用
本文介绍了Python爬虫的高级技术,涵盖并发处理、反爬虫策略(如验证码识别与模拟登录)及数据存储与处理方法。通过asyncio库实现异步爬虫,提升效率;利用tesseract和requests库应对反爬措施;借助SQLAlchemy和pandas进行数据存储与分析。实战部分展示了如何爬取电商网站的商品信息及新闻网站的文章内容。提醒读者在实际应用中需遵守法律法规。
102 66
|
1天前
|
数据采集 存储 JavaScript
构建你的第一个Python网络爬虫
【9月更文挑战第34天】在数字信息泛滥的时代,快速有效地获取和处理数据成为一项重要技能。本文将引导读者通过Python编写一个简易的网络爬虫,实现自动化地从网页上抓取数据。我们将一步步走过代码的编写过程,并探讨如何避免常见陷阱。无论你是编程新手还是想扩展你的技术工具箱,这篇文章都将为你提供有价值的指导。
30 18
|
5天前
|
数据采集 存储 XML
构建高效的Python爬虫系统
【9月更文挑战第30天】在数据驱动的时代,掌握如何快速高效地获取网络信息变得至关重要。本文将引导读者了解如何构建一个高效的Python爬虫系统,从基础概念出发,逐步深入到高级技巧和最佳实践。我们将探索如何使用Python的强大库如BeautifulSoup和Scrapy,以及如何应对反爬措施和提升爬取效率的策略。无论你是初学者还是有经验的开发者,这篇文章都将为你提供宝贵的知识和技能,帮助你在信息收集的海洋中航行得更远、更深。
19 6
|
3天前
|
调度 开发者 网络架构
探索Python中的异步编程:深入理解asyncio库
【9月更文挑战第32天】在现代软件开发中,异步编程已成为提升性能和响应性的关键策略之一。本文将深入探讨Python的asyncio库,一个强大的异步I/O框架,它允许开发者编写单线程并发代码,同时处理多个任务而无需复杂的多线程或多进程编程。通过本文,你将学习到如何利用asyncio来构建高效、可扩展的应用程序,并了解其背后的原理和设计哲学。
7 2
|
4天前
|
数据采集 数据挖掘 数据处理
Python中实现简单爬虫并处理数据
【9月更文挑战第31天】本文将引导读者理解如何通过Python创建一个简单的网络爬虫,并展示如何处理爬取的数据。我们将讨论爬虫的基本原理、使用requests和BeautifulSoup库进行网页抓取的方法,以及如何使用pandas对数据进行清洗和分析。文章旨在为初学者提供一个易于理解的实践指南,帮助他们快速掌握网络数据抓取的基本技能。
15 3
|
5天前
|
数据挖掘 Python
【Python】应用:pyproj地理计算库应用
这篇博客介绍了 `pyproj` 地理计算库的应用,涵盖地理坐标系统转换与地图投影。通过示例代码展示了如何进行经纬度与UTM坐标的互转,并利用 `pyproj.Geod` 计算两点间的距离及方位角,助力地理数据分析。 安装 `pyproj`:`pip install pyproj`。更多内容欢迎关注本博客,一起学习进步! Pancake 🍰 不迷路。😉*★,°*:.☆( ̄▽ ̄)/$:*.°★* 😏
11 1
|
5天前
|
数据采集 Linux 网络安全
python 爬虫遇到的aiohttp证书错误解决办法
python 爬虫遇到的aiohttp证书错误解决办法
20 0
|
6天前
|
数据挖掘 API 数据处理
Python 数据分析及预处理常用库
Python自身数据分析功能有限,需借助第三方库增强。常用库包括NumPy、pandas、Matplotlib等。NumPy由Numeric发展而来,提供了多维数组对象及各种API,支持高效的数据处理,如数学、逻辑运算等,常作为其他高级库如pandas和Matplotlib的依赖库。其内置函数处理速度极快,建议优先使用以提升程序效率。
7 0
|
7天前
|
UED Python
Python requests库下载文件时展示进度条的实现方法
以上就是使用Python `requests`库下载文件时展示进度条的一种实现方法,它不仅简洁易懂,而且在实际应用中非常实用。
19 0
|
7天前
|
机器学习/深度学习 人工智能 数据可视化
# Python的一个非常cool的库Gradio
# Python的一个非常cool的库Gradio
21 0
下一篇
无影云桌面