导入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)