urllib 基本用法 - 图1

基本爬虫

  1. import urllib.request as req
  2. import urllib.parse as parse
  3. import ssl
  4. import json
  5. import time
  6. ssl._create_default_https_context = ssl._create_unverified_context
  7. url = 'https://api-yqzy.mrnaive.com/?s=App.MyUser.GetUserList'
  8. # 打开一个 URL , 获得一个 URL 资源
  9. data = {
  10. 'sign': 'cf1cbd2e142667516d34d570a616ce4b',
  11. 'page': 1,
  12. 'pageNum': 5,
  13. }
  14. head = {
  15. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 '
  16. 'Safari/537.36'
  17. }
  18. while True:
  19. # 将Unicode 资源编码成 utf-8
  20. dataRes = parse.urlencode(data).encode('utf-8')
  21. # request 对象
  22. requestObj = req.Request(url, dataRes, headers = head)
  23. openReq = req.urlopen(requestObj)
  24. # 返回的内容 , 将指定编码解码成 Unicode , 同时将json 转换成字典
  25. res = json.loads(openReq.read().decode('utf-8'))
  26. print(requestObj.headers)
  27. print('结果:', res)
  28. #
  29. print('返回的类型:', type(res))
  30. # 访问地址
  31. print('访问地址:', openReq.geturl())
  32. # 响应头
  33. print('服务器信息:', openReq.info())
  34. # http 状态码
  35. print('http 状态码', openReq.getcode())
  36. time.sleep(1)