python爬虫urliib简单使用

导入urllib

import urllib.request

使用http协议

用url='http://www.baidu.com

模拟浏览器向服务器发送请求,并接受服务器的响应

response=urllib.request.urlopen(url)

获取响应中的页面源码

#read 返回字节形式的二进制源码

#将二进制数据转换为字符串。decode解码

content=response.read().decode('utf-8' )

打印源码

print(content) 

import urllib.request
url='http://www.baidu.com'
#模拟浏览器向服务器发送请求
response=urllib.request.urlopen(url)
content=response.read().decode('utf-8') #返回字节二进制形式
print(content)

 

六个方法
content=response.read(5) #返回5字节
content=response.readline() #一行
content=response.readlines() #按行读取,不可以使用decode
print(response.getcode()) #获得状态码,返回200,逻辑没有错
print(response.getheaders()) #获取状态信息
print(response.geturl()) #返回url地址
一个类型
HTTPResponse

 

 调用 urlretrieve(url,filename)下载资源

import urllib.request

url_img='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2Fb7b81f72-7c4a-462c-9bac-244e2802bbf0%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1689333786&t=1495a38700f22c6bf309e85392ed23fb'

urllib.request.urlretrieve(url=url_img,filename='angelbaby.jpg')

 

 

ua反爬

ua:全名user-agent

#https
import urllib.request
url='https://www.baidu.com'
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}
request=urllib.request.Request(url=url,headers=headers)
response=urllib.request.urlopen(request)
content=response.read().decode('utf-8')
print(content)

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值