python-urllib.request

#get请求访问
import urllib.request

response=urllib.request.urlopen("http://www.baidu.com",timeout=1)#访问相关链接(get请求的方式),返回一个HTTPResponse的对象,timeout为时间限制,超时会产生,urllib.error.urlerror的异常
print(response.read().decode('utf-8'))#read()方法可以获取该网页的源代码 decode()设置成对应的编码,如果不限制编码容易形成乱码
print(response.status)#得到状态码 
# 200:请求成功 301:资源(网页等)被永久转移到其它URL 404:请求的资源(网页等)不存在 418:对方发现你是爬虫了 500:内部服务器错误
print(response.getheaders())#获取请求头
print(response.getheader("Connection"))#获取请求头中特定键值对的信息

#post请求访问
import urllib.request
import urllib.parse#用于解析键值对

data = bytes(urllib.parse.urlencode({
    
    "name":"杨帆"}),encoding="utf-8")#urllib.parse.urlencode()编码相应的键值对,bytes()将相应的数据转换成字节码文件 
response = urllib.request.urlopen("http://  .org/post",data=data)#post请求访问
print(response.read().decode('utf-8'))
#如何防止浏览器发现是爬虫
import urllib.request
import urllib.parse
url="https://movie.douban.com/top250?"
headers={
    
    
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 HBPC/11.0.2.302"
}#模拟真实情况的请求头
data=bytes(urllib.parse.urlencode({
    
    "name":"杨帆"}),encoding="utf-8")
req=urllib.request.Request(url=url,headers=headers,method="get")
response=urllib.request.urlopen(req)
print(response.status)

Guess you like

Origin blog.csdn.net/jahup/article/details/113568138