当前位置:   article > 正文

爬虫基础 & JS逆向

爬虫基础 & JS逆向

爬虫核心

1. HTTP协议与WEB开发

1. 什么是请求头请求体,响应头响应体
2. URL地址包括什么
3. get请求和post请求到底是什么
4. Content-Type是什么

(1)简介

HTTP协议是Hyper Text Transfer Protocol(超文本传输协议)的缩写,是用于万维网(WWW:World Wide Web )服务器与本地浏览器之间传输超文本的传送协议。HTTP是一个属于应用层的面向对象的协议,由于其简捷、快速的方式,适用于分布式超媒体信息系统。它于1990年提出,经过几年的使用与发展,得到不断地完善和扩展。HTTP协议工作于客户端-服务端架构为上。浏览器作为HTTP客户端通过URL向HTTP服务端即WEB服务器发送所有请求。Web服务器根据接收到的请求后,向客户端发送响应信息。

(2)socket套接字

最简单的web应用程序

  1. import socket
  2. sock = socket.socket()
  3. sock.bind(("127.0.0.1", 8890))
  4. sock.listen(3)
  5. print("服务器已经启动...")
  6. while 1:
  7. conn, addr = sock.accept()
  8. data = conn.recv(1024)
  9. print("data:", data)
  10. conn.send(
  11. 'HTTP/1.1 200 ok\r\n\r\n<h1 onClick="alert(\'alex is greened\')" style="color:green">Alex</h1>'.encode())
  12. conn.close()

基于postman完成测试!

(3)请求协议与响应协议

http协议包含由浏览器发送数据到服务器需要遵循的请求协议与服务器发送数据到浏览器需要遵循的请求协议。用于HTTP协议交互的信被为HTTP报文。请求端(客户端)的HTTP报文 做请求报文,响应端(服务器端)的 做响应报文。HTTP报文本身是由多行数据构成的字文本。

一个完整的URL包括:协议、ip、端口、路径、参数

例如: 百度安全验证 其中https是协议,www.baidu.com 是IP,端口默认80,/s是路径,参数是wd=yuan

请求方式: get与post请求

  • GET提交的数据会放在URL之后,以?分割URL和传输数据,参数之间以&相连,如EditBook?name=test1&id=123456. POST方法是把提交的数据放在HTTP包的请求体中.

  • GET提交的数据大小有限制(因为浏览器对URL的长度有限制),而POST方法提交的数据没有限制

响应状态码:状态码的职 是当客户端向服务器端发送请求时, 返回的请求 结果。借助状态码,用户可以知道服务器端是正常 理了请求,还是出 现了 。状态码如200 OK,以3位数字和原因组成。

2. requests&反爬破解

(1)UA反爬

  1. import requests
  2. headers = {
  3. "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
  4. }
  5. res = requests.get(
  6. "https://www.baidu.com/",
  7. # headers=headers
  8. )
  9. # 解析数据
  10. with open("baidu.html", "w") as f:
  11. f.write(res.text)

(2)referer反爬

  1. import requests
  2. headers = {
  3. "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
  4. "Referer": "https://movie.douban.com/explore",
  5. }
  6. res = requests.get(
  7. "https://m.douban.com/rexxar/api/v2/movie/recommend?refresh=0&start=0&count=20&selected_categories=%7B%7D&uncollect=false&tags=",
  8. headers=headers
  9. )
  10. # 解析数据
  11. print(res.text)

(3)cookie反爬

  1. import requests
  2. url = "https://stock.xueqiu.com/v5/stock/screener/quote/list.json?page=1&size=30&order=desc&orderby=percent&order_by=percent&market=CN&type=sh_sz"
  3. cookie = 'xq_a_token=a0f5e0d91bc0846f43452e89ae79e08167c42068; xqat=a0f5e0d91bc0846f43452e89ae79e08167c42068; xq_r_token=76ed99965d5bffa08531a6a47501f096f61108e8; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTY5NTUxNTc5NCwiY3RtIjoxNjkzMjAzODIzMzAwLCJjaWQiOiJkOWQwbjRBWnVwIn0.MCIGGTGaSPe9nVuXkyrXQTlCthdURSnDtqm8dGttO2XYHeaMPSKmHQvsJmbw3OJTRnkf0KHZvgF0W3Rv-9uYe4P2Wizt0g2QzQonONjUmExABmZX0e3ara8BzBQ3b96H7dm0LV4pdBlnOW0A9PUmGRouWM7kVUOGPvd3X7GkB7M_th8pV8SZo9Iz4nzjrwQzxPBa0DlS7whbeNeXMnbnmAPp7z-eG75vdE2Pb3OyZ5Gv-FINhpQtAWo95lTxZVw5C5VHSzbR_-z8uqH6DD0xop4_wvKw5LIVwu6ZZ6TUnNFr3zGU9jWqAGgdzcKgO38dlL6uXNixa9mrKOd1OZnDig; cookiesu=431693203848858; u=431693203848858; Hm_lvt_1db88642e346389874251b5a1eded6e3=1693203851; device_id=7971eba10048692a91d87e3dad9eb9ca; s=bv11kb1wna; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1693203857'
  4. headers = {
  5. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
  6. "referer": "https://xueqiu.com/",
  7. "cookie": cookie,
  8. }
  9. res = requests.get(url, headers=headers)
  10. print(res.text)

3. 请求参数

(1)get请求以及查询参数

(2)post请求以及请求体参数

  1. import requests
  2. while 1:
  3. wd = input("请输入翻译内容:")
  4. res = requests.post("https://aidemo.youdao.com/trans?", params={}, headers={},
  5. data={
  6. "q": wd,
  7. "from": "Auto",
  8. "to": "Auto"
  9. })
  10. print(res.json().get("translation")[0])

4. 爬虫图片和视频

(1)直接爬取媒体数据流

  1. import requests
  2. # (1)下载图片
  3. url = "https://pic.netbian.com/uploads/allimg/230812/202108-16918428684ab5.jpg"
  4. res = requests.get(url)
  5. # 解析数据
  6. with open("a.jpg", "wb") as f:
  7. f.write(res.content)
  8. # (2)下载视频
  9. url = "https://vd3.bdstatic.com/mda-nadbjpk0hnxwyndu/720p/h264_delogo/1642148105214867253/mda-nadbjpk0hnxwyndu.mp4?v_from_s=hkapp-haokan-hbe&auth_key=1693223039-0-0-e2da819f15bfb93409ce23540f3b10fa&bcevod_channel=searchbox_feed&pd=1&cr=2&cd=0&pt=3&logid=2639522172&vid=5423681428712102654&klogid=2639522172&abtest=112162_5"
  10. res = requests.get(url)
  11. # 解析数据
  12. with open("美女.mp4", "wb") as f:
  13. f.write(res.content)

(2)批量爬取数据

  1. import requests
  2. import re
  3. import os
  4. # (1)获取当页所有的img url
  5. start_url = "https://pic.netbian.com/4kmeinv/"
  6. res = requests.get(start_url)
  7. img_url_list = re.findall("uploads/allimg/.*?.jpg", res.text)
  8. print(img_url_list)
  9. # (2)循环下载所有图片
  10. for img_url in img_url_list:
  11. res = requests.get("https://pic.netbian.com/" + img_url)
  12. img_name = os.path.basename(img_url)
  13. with open(img_name, "wb") as f:
  14. f.write(res.content)

5. 打码平台

获取验证码

打码平台:图鉴

  1. import base64
  2. import json
  3. import requests
  4. def base64_api(uname, pwd, img, typeid):
  5. with open(img, 'rb') as f:
  6. base64_data = base64.b64encode(f.read())
  7. b64 = base64_data.decode()
  8. data = {"username": uname, "password": pwd, "typeid": typeid, "image": b64}
  9. result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text)
  10. if result['success']:
  11. return result["data"]["result"]
  12. else:
  13. # !!!!!!!注意:返回 人工不足等 错误情况 请加逻辑处理防止脚本卡死 继续重新 识别
  14. return result["message"]
  15. if __name__ == "__main__":` img_path = "./v_code.jpg"
  16. result = base64_api(uname='yuan0316', pwd='yuan0316', img=img_path, typeid=3)
  17. print(result)

6. 今日作业

动手练习:模拟登陆

JS逆向实战案例1

URL地址:https://user.wangxiao.cn/login?url=http%3A%2F%2Fks.wangxiao.cn%2F

1、抓包分析登录请求时,发现请求体“password”被加密

2、可以搜索请求体内容找到对应源代码部分,这里选择使用访问的url去搜索

3、这里搜索到3处地方,无法判断具体是哪一块的源代码,可以都添加上断点,再次点击登陆。看源代码会停在哪个位置。

4、找到源代码,看到password是由“密码 + 10位的时间戳”,再使用encryptFn函数进行处理。

5、再点击找到js函数源代码,刚刚查到的密码不是这个长字符串,判断使用base64对password进行了编码,再使用RSA加密算法进行的加密。

(1)获取验证码

  1. import requests
  2. import base64
  3. import json
  4. def base64_api(b64):
  5. data = {"username": "bb328410948", "password": "bb328410948", "typeid": 3, "image": b64}
  6. result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text)
  7. if result['success']:
  8. return result["data"]["result"]
  9. else:
  10. return result["message"]
  11. session = requests.session()
  12. session.headers = {
  13. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
  14. }
  15. # 进入登录页, 目的: 加载cookie
  16. login_url = "https://user.wangxiao.cn/login?url=http%3A%2F%2Fks.wangxiao.cn%2F"
  17. session.get(login_url)
  18. session.headers['Content-Type'] = "application/json;charset=UTF-8"
  19. # 下载验证码图片
  20. verify_img_url = "https://user.wangxiao.cn/apis//common/getImageCaptcha"
  21. img_resp = session.post(verify_img_url).json().get("data")
  22. img_b64 = img_resp.split(",")[-1]
  23. print(img_b64)
  24. with open("code.png", mode="wb") as f:
  25. f.write(base64.b64decode(img_b64))
 

(2)JS逆向密码加密

rsa非对称加密:

  1. from Crypto.PublicKey import RSA
  2. from Crypto.Cipher import PKCS1_v1_5
  3. import base64
  4. # (1)创建公钥私钥
  5. # rsakey = RSA.generate(1024)
  6. #
  7. # with open("rsa.public.pem", mode="wb") as f:
  8. # f.write(rsakey.publickey().exportKey())
  9. #
  10. # with open("rsa.private.pem", mode="wb") as f:
  11. # f.write(rsakey.exportKey())
  12. # (2)加密
  13. data = "我喜欢好多女孩"
  14. with open("rsa.public.pem", mode="r") as f:
  15. pk = f.read()
  16. rsa_pk = RSA.importKey(pk)
  17. rsa = PKCS1_v1_5.new(rsa_pk)
  18. result = rsa.encrypt(data.encode("utf-8"))
  19. print("原生加密:", result)
  20. # 处理成b64方便传输
  21. b64_result = base64.b64encode(result).decode("utf-8")
  22. print("rsa加密数据:", b64_result)
  23. # (3)解密:私钥
  24. data = "JRI0YcnIVQ6elt6lKnNGxmBOaFRb4vkcj5vO6z5/bEvEB8WgHvjmHag6kaDQNXLDsISWR8bEjBhy7m78RGaDmEchVam7Bl1UXFhMq3YeQ6bqsGf+lKHtC8eYN5MJAeJ8vYUOVY3gShKhMT+WVfmIdEWFIrRM1Z6p3AGH3Qrq+0U="
  25. ret = base64.b64decode(data.encode())
  26. with open("rsa.private.pem", mode="r") as f:
  27. prikey = f.read()
  28. rsa_pk = RSA.importKey(prikey)
  29. rsa = PKCS1_v1_5.new(rsa_pk)
  30. result = rsa.decrypt(ret, None)
  31. print("rsa解密数据:::", result.decode("utf-8"))
 
  1. import requests
  2. import base64
  3. import json
  4. from Crypto.PublicKey import RSA
  5. from Crypto.Cipher import PKCS1_v1_5
  6. def base64_api(b64):
  7. data = {"username": "yuan0316", "password": "yuan0316", "typeid": 3, "image": b64}
  8. result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text)
  9. if result['success']:
  10. return result["data"]["result"]
  11. else:
  12. return result["message"]
  13. return ""
  14. # 为了保持cookie状态
  15. # 所有的服务器返回的set-cookie都可以自动帮你保存和更新
  16. # js动态添加的cookie 它无法保持..
  17. # 如果你手动添加了cookie信息. 后续请求都会保持该cookie
  18. session = requests.session()
  19. # # 如果遇到了js动态加载的cookie. 可以使用下面这个方案来手动保持.
  20. # session.cookies['abc'] = "123456"
  21. session.headers = {
  22. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
  23. }
  24. # 进入登录页, 目的: 加载cookie
  25. login_url = "https://user.wangxiao.cn/login?url=http%3A%2F%2Fks.wangxiao.cn%2F"
  26. session.get(login_url)
  27. # 根据实际案例来尝试.
  28. # 一次搞定(后续的请求不能有html的请求)
  29. session.headers['Content-Type'] = "application/json;charset=UTF-8"
  30. # 下载验证码图片
  31. verify_img_url = "https://user.wangxiao.cn/apis//common/getImageCaptcha"
  32. img_resp = session.post(verify_img_url)
  33. img_resp_json = img_resp.json()
  34. img_base64 = img_resp_json.get("data").split(",")[-1]
  35. with open("tu.png", mode="wb") as f:
  36. f.write(base64.b64decode(img_base64))
  37. # 识别验证码
  38. verify_code = base64_api(img_base64)
  39. print(verify_code)
  40. # 在加密之前, 需要访问getTime, 获取到一个时间.
  41. getTime_url = "https://user.wangxiao.cn/apis//common/getTime"
  42. getTime_resp = session.post(getTime_url)
  43. getTime_json = getTime_resp.json()
  44. getTime = getTime_json.get('data')
  45. login_name = "13121758648"
  46. password_ming = "13121758648yuan"
  47. # 对密码进行加密
  48. # rsa加密(密码+时间)
  49. # rsa的公钥: "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA5Zq6ZdH/RMSvC8WKhp5gj6Ue4Lqjo0Q2PnyGbSkTlYku0HtVzbh3S9F9oHbxeO55E8tEEQ5wj/+52VMLavcuwkDypG66N6c1z0Fo2HgxV3e0tqt1wyNtmbwg7ruIYmFM+dErIpTiLRDvOy+0vgPcBVDfSUHwUSgUtIkyC47UNQIDAQAB"
  50. # 把公钥处理成字节
  51. rsa_key_bs = base64.b64decode("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA5Zq6ZdH/RMSvC8WKhp5gj6Ue4Lqjo0Q2PnyGbSkTlYku0HtVzbh3S9F9oHbxeO55E8tEEQ5wj/+52VMLavcuwkDypG66N6c1z0Fo2HgxV3e0tqt1wyNtmbwg7ruIYmFM+dErIpTiLRDvOy+0vgPcBVDfSUHwUSgUtIkyC47UNQIDAQAB")
  52. # 加载公钥
  53. pub_key = RSA.importKey(rsa_key_bs)
  54. # 创加密器
  55. rsa = PKCS1_v1_5.new(pub_key)
  56. # 进行rsa加密, 加密的内容是 密码+时间
  57. password_mi_bs = rsa.encrypt((password_ming+getTime).encode("utf-8"))
  58. # 加密后的字节. 处理成base64
  59. password_mi = base64.b64encode(password_mi_bs).decode()
  60. # 登陆需要的参数备齐了. 可以开始登陆了
  61. login_data = {
  62. "imageCaptchaCode": verify_code,
  63. "password": password_mi,
  64. "userName": login_name
  65. }
  66. password_login_url = "https://user.wangxiao.cn/apis//login/passwordLogin"
  67. login_resp = session.post(password_login_url, data=json.dumps(login_data))
  68. login_json = login_resp.json()
  69. login_success_data = login_json.get("data")

注意点:

1、POST访问方式请求体类型,request.post默认为urlencoding表单格式,请求体的类型为json格式时,需要使用json.dumps(data)

2、一般,当网页需要跳转访问时,会验证是否携带cookie,使用以下方式可以实现cookie的自动添加

  1. # 自动保存cookie
  2. session = requests.session()
  3. # 添加请求头
  4. session.headers = {
  5. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
  6. }
  7. # 进入首页,加载cookie
  8. session.get(login_url)
  9. # 后续再使用session.get/post访问二级页面时,将会自动添加cookie

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/998616
推荐阅读
相关标签
  

闽ICP备14008679号