2021-08-09

爬虫训练网站

基础爬虫训练

import urllib.request
respone = urllib.request.urlopen("http://www.baidu.com")
print(respone.read().decode('utf-8'))

超时处理

try:
    respone = urllib.request.urlopen("http://www.baidu.com",timeout=0.1)
except urllib.error.URLError as chaoshi:
    print("超时!")		#超过0.1s打印超时

欺骗服务器
在这里插入图片描述
418表示不让爬虫

import urllib.request
url = "http://httpbin.org/get"
respone = urllib.request.urlopen(url)
print(respone.read().decode('utf-8'))

返回
在这里插入图片描述
上面User-Agent 直接表明我们是Python,所以我们可以用Post传递表单,将User-Agent设置为浏览器访问时的用户代理

import urllib.parse,urllib.request
url = "http://httpbin.org/post"
headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) ..."

}
#数据data在form中体现
data = bytes(urllib.parse.urlencode({"name":"123"}),encoding="utf-8")
#设置请求对象
res = urllib.request.Request(url = url, data = data, headers = headers, method= "POST")
respone = urllib.request.urlopen(res)
print(respone.read().decode('utf-8'))

在这里插入图片描述
显示User-Agent为浏览器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值