urllib库与爬虫的简单示例程序

示例:urlopen的使用

import urllib.request


url = 'http://www.baidu.com'
with urllib.request.urlopen(url) as res:
    html = res.read()
    print(type(html))
    print(html)

执行代码,可以看到这段程序把整个百度首页的html代码全部下载下来了,没有经过任何解析。

Request类对象

import urllib.request


url = 'https://www.baidu.com'
request=urllib.request.Request(url)
res = urllib.request.urlopen(request)
html = res.read()
print(type(html))
print(html)

利用url构造了一个Request类对象,并用这个类对象作为urlopen的参数获得响应,这段程序的结果与上例相同。

构造User-Agent

import urllib.request

# 构造request
url = 'https://www.baidu.com'
ua = {'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'}
request=urllib.request.Request(url,headers=ua)

# 读取数据
res = urllib.request.urlopen(request)
print(type(res))
html = res.read().decode()  # 使用.decode()可以将获得的数据由bytes转换为str
print(type(html))
print(html)
# ctrl+/ 注释代码块

注意.decode()的使用,使bytes->str。

url中字符的编码与解码
编码需要使用urllib.request.urlencode方法

发布了38 篇原创文章 · 获赞 9 · 访问量 6301

猜你喜欢

转载自blog.csdn.net/qq_42138454/article/details/104106387