爬虫第一次笔记 urllib的基本使用 urllib一个类型,六个方法 urllib下载 urllib请求对象的定制

urllib的基本使用

使用urllib获取百度首页的源码

# 1. 定义一个url (指的就是要访问的地址)
url = "http://www.baidu.com"

# 2. 模拟浏览器向服务器发送请求
response = urllib.request.urlopen(url)

# 3. 获取响应中的页面的源码
# 将二进制数据转换成字符串
content = response.read().decode("utf-8")

# 4. 打印数据
print(content)

urllib一个类型,六个方法

一个类型 HTTPResponse
六个方法 read readline readlines getcode geturl getheaders

import urllib.request
# 一个类型 HTTPResponse
# 六个方法 read readline readlines getcode geturl getheaders
url = "http://www.baidu.com"
response = urllib.request.urlopen(url)

# 一个类型和六个方法
# print(type(response))

# 按照一个字节一个字节读取
# content = response.read()
#
# print(content)

# content = response.read(5)
#
# print(content)

content = response.readlines()
print(content)

print(response.getcode())

print(response.geturl())
print(response.getheaders())

urllib下载

下载网页

# 下载网页
url_page = "http://www.baidu.com"
urllib.request.urlretrieve(url_page,"baidu.html")

下载图片

# 下载图片
url_img = "https://img0.baidu.com/it/u=2759579759,1586116829&fm=253&fmt=auto&app=120&f=JPEG?w=717&h=448"
urllib.request.urlretrieve(url_img,"lisa.jpg")

下载视频
获取视频的方法
在这里插入图片描述

url_video = "https://www.douyin.com/aweme/v1/play/?video_id=v0200fg10000ccna27rc77ub11dta7cg&line=0&file_id=9b13590c62a8455b8a68a95cdef94734&sign=53bdf54b5862fbd847152cbb7d8d85e3&is_play_url=1&source=PackSourceEnum_AWEME_DETAIL&aid=6383"
urllib.request.urlretrieve(url_video,"erya.mp4")

urllib请求对象的定制

这个就是突破第一个反爬手段
网址的组成

# url的组成
# 协议 http / https
# 主机 www.badu.com
# 端口号 80
# 路径 s
# 参数 ie=utf-8&f=8&rsv_bp=1&tn=02003390_43_hao
# 锚点 #

这一次测试是https协议开头的,不是http,如果还是和之前一样进行爬取,是获取不到的。
所以得给参数添加自己的User-Agent

先导包

import urllib.request

url = "https://www.baidu.com"

之后模拟出一个AU,假装是真正的浏览器访问,

headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36"
}
# 因为url open方法中不能存储字典,所以header不能传入,
request = urllib.request.Request(url=url,headers=headers)
response = urllib.request.urlopen(request)
content = response.read().decode("utf-8")
print(content)
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花花叔叔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值