广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python爬虫之Urllib库的基本使
  • 452
分享到

Python爬虫之Urllib库的基本使

爬虫PythonUrllib 2023-01-30 22:01:53 452人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

# get请求 import urllib.request response = urllib.request.urlopen("Http://www.baidu.com") print(response.read().decode('

# 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")
 1 # 解析URL
 2 # urlparse
 3 from urllib.parse import urlparse
 4 result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
 5 print(type(result), result)
 6 
 7 from urllib.parse import urlparse
 8 result = urlparse('www.baidu.com/index.html;user?id=5#comment', scheme = "https")
 9 print(result)
10 
11 from urllib.parse import urlparse
12 result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', scheme = "https")
13 print(result)
14 
15 from urllib.parse import urlparse
16 result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', allow_fragments = False)
17 print(result)
18 
19 from urllib.parse import urlparse
20 result = urlparse('http://www.baidu.com/index.html#comment', allow_fragments = False)
21 print(result)
 1 # urlunparse
 2 from urllib.parse import urlunparse
 3 data = ['http', 'www.baidu.com', 'index,html', 'user', 'a=6', 'comment']
 4 print(urlunparse(data))
 5 
 6 # urljoin
 7 from urllib.parse import urljoin
 8 print(urljoin('http://www.baidu.com', 'FAQ.html'))
 9 print(urljoin('http://www.baidu.com', 'https://cuiqinGCai.com/FAQ.html'))
10 print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html'))
11 print(urljoin('http://www.baidu.com/about.html', 'http://cuiqingcai.com/FAQ.html?question=2'))
12 print(urljoin('http://www.baidu.com?wd=abc', 'https://cuiqingcai.com/index.PHP'))
13 print(urljoin('http://www.baidu.com', '?cateGory=2#comment'))
14 print(urljoin('www.baidu.com', '?category=2#comment'))
15 print(urljoin('www.baidu.com#comment', '?category=2'))
16 
17 # urlencode
18 from urllib.parse import urlencode
19 params = {
20     'name':'germey',
21     'age':22
22 }
23 base_url = 'http://www.baidu.com'
24 url = base_url + urlencode(params)
25 print(url)

 

--结束END--

本文标题: Python爬虫之Urllib库的基本使

本文链接: https://www.lsjlt.com/news/180378.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python爬虫之Urllib库的基本使
    # get请求 import urllib.request response = urllib.request.urlopen("http://www.baidu.com") print(response.read().decode('...
    99+
    2023-01-30
    爬虫 Python Urllib
  • python爬虫之请求模块urllib的基本使用
    目录前言urllib的子模块HttpResponse常用方法与属性获取信息urlli.parse的使用(一般用于处理带中文的url)✅爬取baidu官网HTML源代码✅添加请求头信息...
    99+
    2022-11-10
  • Python爬虫之urllib库详解
    目录一、说明:二、urllib四个模块组成:三、urllib.request1、urlopen函数2、response 响应类型3、Request对象 4、高级请求方式四、urlli...
    99+
    2022-11-13
  • Python爬虫进阶之如何使用urllib库
    这篇文章主要介绍了Python爬虫进阶之如何使用urllib库,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。python的数据类型有哪些python的数据类型:1. 数字类型...
    99+
    2023-06-14
  • Python爬虫之requests库基本介绍
    目录一、说明二、基本用法:总结一、说明 requests是一个很实用的Python HTTP客户端库,爬虫和测试服务器响应数据时经常会用到,requests是Python语言的第三方...
    99+
    2022-11-13
  • Python爬虫之Requests库的基
    1 import requests 2 response = requests.get('http://www.baidu.com/') 3 print(type(response)) 4 print(response....
    99+
    2023-01-30
    爬虫 Python Requests
  • Python爬虫库urllib的使用教程详解
    目录Python urllib库urllib.request模块urlopen函数Request 类urllib.error模块URLError 示例HTTPError示例...
    99+
    2022-11-21
    Python爬虫库urllib使用 Python urllib使用 Python urllib
  • Python爬虫之BeautifulSoup的基本使用教程
    目录bs4的安装bs4的快速入门解析器的比较(了解即可)对象种类bs4的简单使用获取标签内容获取标签名字获取a标签的href属性值遍历文档树案例练习思路代码实现总结bs4的安装 要使...
    99+
    2022-11-13
  • python爬虫urllib库中parse模块urlparse的使用方法
    这篇文章主要介绍了python爬虫urllib库中parse模块urlparse的使用方法,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。在python爬虫urllib库中,u...
    99+
    2023-06-14
  • Python爬虫基础之初次使用scrapy爬虫实例
    项目需求 在专门供爬虫初学者训练爬虫技术的网站(http://quotes.toscrape.com)上爬取名言警句。 创建项目 在开始爬取之前,必须创建一个新的Scrapy项目。进入您打算存储代码的目录中,运行下列...
    99+
    2022-06-02
    Python scrapy框架 Python爬虫
  • Python爬虫基础之selenium库怎么用
    小编给大家分享一下Python爬虫基础之selenium库怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!一、selenium简介官网总的来说: seleni...
    99+
    2023-06-15
  • Python3 Urllib库的基本使用
    一、什么是Urllib   Urllib库是Python自带的一个http请求库,包含以下几个模块: urllib.request    请求模块 urllib.error        异常处理模块 urllib.parse      ...
    99+
    2023-01-31
    Urllib
  • Python爬虫基础之爬虫的分类知识总结
    目录一、通用爬虫二、搜索引擎的局限性三、Robots协议四、请求与相应一、通用爬虫 通用网络爬虫是搜索引擎抓取系统(Baidu、Google、Sogou等)的一个重要组成部分。主要目...
    99+
    2022-11-12
  • Python爬虫基础之selenium库的用法总结
    目录一、selenium简介二、selenium基本用法三、常用用法四、cookie的设置、获取与删除五、文件的上传与下载 文件上传upload六、窗口的切换七、项目实战一、selenium简介 官网 总的来说: ...
    99+
    2022-06-02
    Python selenium库用法 python爬虫
  • 详解Python爬虫的基本写法
    什么是爬虫 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来。想抓取什么?这个由你来控制它咯。 比如它在...
    99+
    2022-06-04
    爬虫 写法 详解
  • python爬虫之requests库的使用详解
    目录python爬虫—requests库的用法基本的get请求带参数的GET请求:解析json使用代理获取cookie会话维持证书验证设置超时异常捕获异常处理 总结 python爬虫...
    99+
    2022-11-12
  • python爬虫之pyppeteer库简单使用
    pyppeteer 介绍Pyppeteer之前先说一下Puppeteer,Puppeteer是谷歌出品的一款基于Node.js开发的一款工具,主要是用来操纵Chrome浏览器的 AP...
    99+
    2022-11-12
  • python爬虫之requests库使用代理方式
    目录安装上requests库GET方法谷歌浏览器的开发者工具POST方法使用代理在看这篇文章之前,需要大家掌握的知识技能: python基础html基础http状态码 让我们看看这篇...
    99+
    2022-11-11
  • 使用Python的urllib和urllib2模块制作爬虫的实例教程
    urllib 学习python完基础,有些迷茫.眼睛一闭,一种空白的窒息源源不断而来.还是缺少练习,遂拿爬虫来练练手.学习完斯巴达python爬虫课程后,将心得整理如下,供后续翻看.整篇笔记主要分以下几个部...
    99+
    2022-06-04
    爬虫 实例教程 模块
  • Python爬虫基础之请求的示例分析
    小编给大家分享一下Python爬虫基础之请求的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!一、请求目标(URL)URL又叫作统一资源定位符,是用于完整地...
    99+
    2023-06-15
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作