Python爬虫项目
用urlopen发送http get请求
import urllib.request
response=urllib.request.urlopen("https://www.cnblogs.com")
#用utf-8解码
print(response.read().decode('utf-8'))
京东项目实战
获取HTTP报文信息
import urllib.request
response=urllib.request.urlopen("https://www.jd.com")
print("response的类型:",type(response))
print("status:",response.status," msg:",response.msg," version",response.version)
print('header:',response.headers," \n\n",response.getheaders())
print('headers-content-type:',response.getheader('Content-Type'))
print(response.read().decode('utf-8'))
用urlopen发送HTTP post请求
需要将数据转换为bytes类型
import urllib.request
data=bytes(urllib.parse.urlencode({'name':'Bill','age':30}),encoding='utf-8')
response=urllib.request.urlopen('http://httpbin.org/post',data=data)
print(response.read().decode('utf-8'))
使用try except捕获超时异常
import urllib.request
import socket
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):
#isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。
print('超时')
print('continue....')
设置HTTP请求头
#修改了user-agent和host请求头,并且添加了自定义请求头,并提交给了web
from urllib import request,parse
url="http://httpbin.org/post"
headers={
"User-Agent":"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.7113.93 Safari/537.36",
"Host":"127.0.0.1",
"who":'my python'
}
dict={
'name':'Bill',
'age':30
}
data=bytes(parse.urlencode(dict),encoding='utf-8')
req=request.Request(url=url,data=data,headers=headers)
print(str(req)+"\n\n")
response=request.urlopen(req)
print(response.read().decode('utf-8'))
作者:Zeker62
出处:https://www.cnblogs.com/Zeker62/p/15227504.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 领域驱动设计实战:聚合根设计与领域模型实现
· 突破Excel百万数据导出瓶颈:全链路优化实战指南
· 如何把ASP.NET Core WebApi打造成Mcp Server
· Linux系列:如何用perf跟踪.NET程序的mmap泄露
· 日常问题排查-空闲一段时间再请求就超时
· .NET周刊【5月第1期 2025-05-04】
· Python 3.14 新特性盘点,更新了些什么?
· 聊聊 ruoyi-vue ,ruoyi-vue-plus ,ruoyi-vue-pro 谁才是真正的
· 物联网之对接MQTT最佳实践
· Redis 连接池耗尽的一次异常定位