python爬虫-urllib

这节课来学习一下什么是urllib库

功能:指定URL,获取网页数据(给网页就能爬)

获取到的网页原始数据需要后续的处理:

1.解析为树形(需要用到BeautifulSoup,方法见咱的另一篇博客

2.粗略提取需要爬取的信息(通过树的各种及节点粗略爬取需要的数据,网页简单时可省略)

3.精确定位(通过正则表达式精确匹配信息,方法见咱的另一篇博客

4.保存有用信息(保存到文件,excle,数据库等)

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
# 测试urllib

import urllib.request

# 获取一个get请求(无需提供信息)
response = urllib.request.urlopen("http://www.baidu.com")   # response网页对象,需要二次操作
print(response)
print(response.read())  # 读取网页(二进制文件,未用浏览器解析)
print(response.read().decode('utf-8'))  # 解码(换行符中文都能正常解释),html格式,结构清晰


# 获取一个post请求(向服务器提供一个表单)
import urllib.parse

# 传递参数(用户名、密码等)二进制格式
# 将键值对以"utf-8"的方式解析封装==>>转化为二进制包
data = bytes(urllib.parse.urlencode({"hello":"world"}).encode("utf-8"))
response = urllib.request.urlopen("http://httpbin.org/post", data=data)
print(response.read().decode("utf-8"))


# 超时问题
timeout= :若响应时间超出设定值,则自动停止
try:
    response = urllib.request.urlopen("http://httpbin.org/get", timeout=0.01)
    print(response.read().decode("utf-8"))
except urllib.error.URLError as e:  # 超时检测
    print('time out!',e)


# 网页信息查询(除了网页信息还有很多其他信息)
response = urllib.request.urlopen("http://www.baidu.com")  # 所有返回的信息
print(response.status)  # 获取网页状态码:200(正常);404(找不到);418(发现被爬)
print(response.getheaders())    # 头部信息
print(response.getheader('Server'))    # 头部信息具体某条内容


# 伪装成浏览器
# 先伪装信息,再提交给浏览器
# 不能像前面直接访问,无法包含伪装信息
# 用req对象包装一下
url = "http://httpbin.org/post"
# data:提交信息(同上)
data = bytes(urllib.parse.urlencode({"hello": "world"}).encode("utf-8"))
# headers:伪装成浏览器
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 "

                  "Safari/537.36 "

}
# 封装请求对象(包含网址、封装信息、头部信息、传递方式等)
req = urllib.request.Request(url=url, data=data, headers=headers, method='POST')    # method:访问方式
response = urllib.request.urlopen(req)  # 提交
print(response.read().decode('utf-8'))


# 伪装成浏览器访问豆瓣
url = "http://www.douban.com"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 "

                  "Safari/537.36 "

}
req = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(req)
print(response.read().decode('utf-8'))

你学会了吗?

猜你喜欢

转载自blog.csdn.net/weixin_40960364/article/details/106228110
今日推荐