1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| #!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :spider @File :testUrllib.py @Author :txy @Date :2022/11/16 18:24 '''
import urllib.request
# 获取一个get请求 # response = urllib.request.urlopen("http://www.baidu.com") # print(response.read().decode("utf-8")) # 使用utf-8将二进制编码解码
import urllib.parse # 获取post请求 # data = bytes(urllib.parse.urlencode({"hellow":"word"}), encoding="utf-8") # response = urllib.request.urlopen("https://httpbin.org/post", data=data) # https://httpbin.org接口测试网站 # print(response.read().decode("utf-8"))
# response = urllib.request.urlopen("https://httpbin.org/get", timeout=0.01) # 超时时退出本程序 # print(response.read().decode('utf-8'))
# response = urllib.request.urlopen("https://www.zhihu.com/") # print(response.getheaders())
url = 'https://movie.douban.com/top250?start=0' headers ={ 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' } data = bytes(urllib.parse.urlencode({'name':'eric'}), encoding='utf-8') req = urllib.request.Request(url=url, data=data, headers=headers, method="POST") res = urllib.request.urlopen(req) print(res.read().decode('utf-8'))
# url='https://movie.douban.com/top250?start=0' # headers={ # 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' # } # data = bytes(urllib.parse.urlencode({'name':'jay'}),encoding='utf-8') # req = urllib.request.Request(url=url,data=data,headers=headers,method='POST') # response = urllib.request.urlopen(req) # print(response.read().decode('utf-8'))
|