Python基础获取页面源规则

# -*- coding = utf-8 -*-
# @Time : 2022/7/25 19:19
# @Author : khm
# @File : testurllib.py
# @Software : PyCharm
import urllib.request
import urllib.parse
import codecs

'''
# 获取一个get请求
response = urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode("utf-8"))  # 对获取到的网页源码进行utf-8解码
'''
'''
# 获取一个post请求
data = bytes(urllib.parse.urlencode({"hello": "world"}), encoding="utf-8")
response = urllib.request.urlopen("http://httpbin.org/post", data=data)
print(response.read().decode("utf-8"))  # 对获取到的网页源码进行utf-8解码
'''
'''
# 超时处理
try:
    response = urllib.request.urlopen("http://httpbin.org/get", timeout=0.01)
    print(response.read().decode("utf-8"))  # 对获取到的网页源码进行utf-8解码
except urllib.error.URLError as e:
    print("time out!")
'''
'''
try:
    response = urllib.request.urlopen("http://www.baidu.com", timeout=5)
    print(response.status)  # 对获取到的网页源码进行utf-8解码
    print(response.getheaders())  # 对获取到的网页源码进行utf-8解码
except Exception as e:
    print(e)
'''
# 伪装自己是人
# 爬取首页并写入文件
url = "http://www.douban.com"
data = bytes(urllib.parse.urlencode({"username": "khm"}).encode("utf-8"))
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
}
req = urllib.request.Request(url=url, data=data, headers=headers, method="POST")
response = urllib.request.urlopen(req, timeout=5)
# print(response.read().decode("utf-8"))
f = open('douban_index.html', mode="w", encoding="utf-8")
f.write(response.read().decode("utf-8"))
f.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

康梓潼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值