mikeee 发表于 2020-4-23 18:16

一行代码实现52pojie的自动签到

本帖最后由 mikeee 于 2020-5-1 22:41 编辑

```python
import httpx, browser_cookie3, pyquery

url = "https://www.52pojie.cn/home.php?mod=task&do=draw&id=2"
# url = "https://www.52pojie.cn/home.php?mod=task&do=apply&id=2"
try:
    print(pyquery.PyQuery(httpx.get(url, cookies=browser_cookie3.chrome(domain_name="www.52pojie.cn")).text)("#messagetext")("p").text())
except Exception as exc:
    raise SystemExit(exc)
```
异步版(速度更快、更可靠)
```python
import asyncio, httpx, browser_cookie3

urls = [
    "https://www.52pojie.cn/home.php?mod=task&do=draw&id=2",
    "https://www.52pojie.cn/home.php?mod=task&do=apply&id=2",
]

try:
    print(any(["wbs.png" in elm.text for elm in asyncio.get_event_loop().run_until_complete(asyncio.gather(httpx.AsyncClient(timeout=10, cookies=browser_cookie3.chrome(domain_name="www.52pojie.cn")).get(urls), httpx.AsyncClient(timeout=10, cookies=browser_cookie3.chrome(domain_name="www.52pojie.cn")).get(urls)))]))
except Exception as exc:
    print(exc)
```
看到另一帖“ji行代码实现52pojie的自动签到”一时兴起 —— 对,你没看错,就一行码(不算导入第三方库以及异常检测)。无需人工拷cookies。觉得有用就免费评个分什么的。有必要的话我可以打个包给没有python环境的网友用。其实我自己也不用,基本每天来这里逛一下顺便签个到,版主别罚我,如果不妥请移除。

masterkoko 发表于 2020-4-23 19:27

冰棍好烫啊 发表于 2020-4-23 18:44
明白了            .

Chrome 的Cookie放在F:\Users\<用户名>\AppData\Local\Google\Chrome\User Data\Default\Cookies文件中,这个文件是一个sqlite数据库,可以随便找个数据库管理工具打开它

mikeee 发表于 2020-4-23 19:57

本帖最后由 mikeee 于 2020-4-23 20:02 编辑

masterkoko 发表于 2020-4-23 19:27
Chrome 的Cookie放在F:%users\\AppData\Local\Google\Chrome%user Data\Default\Cookies文件中,这个文件 ...
其实也不是随便打开就能读出来的。https://pastebin.ubuntu.com/p/hgDk494z45/ 我写的读Chrome浏览器 cookies的程序。
```python
"""

http://www.programmersought.com/article/41052167991/
snippets get-baidu-cookies.py

cursor = conn.execute("PRAGMA table_info(cookies)"):
cursor.fetchal()
[(0, 'creation_utc', 'INTEGER', 1, None, 0),
(1, 'host_key', 'TEXT', 1, None, 0),
(2, 'name', 'TEXT', 1, None, 0),
(3, 'value', 'TEXT', 1, None, 0),
(4, 'path', 'TEXT', 1, None, 0),
(5, 'expires_utc', 'INTEGER', 1, None, 0),
(6, 'is_secure', 'INTEGER', 1, None, 0),
(7, 'is_httponly', 'INTEGER', 1, None, 0),
(8, 'last_access_utc', 'INTEGER', 1, None, 0),
(9, 'has_expires', 'INTEGER', 1, '1', 0),
(10, 'is_persistent', 'INTEGER', 1, '1', 0),
(11, 'priority', 'INTEGER', 1, '1', 0),
(12, 'encrypted_value', 'BLOB', 0, "''", 0),
(13, 'samesite', 'INTEGER', 1, '-1', 0),
(14, 'source_scheme', 'INTEGER', 1, '0', 0)]

_ = CIMultiDict({'domain': '.baidu.com', 'names': ['*'],
'copyto': True, 'cookies': False, 'debug': True})
for elm in _:
    globals() = _.get(elm)
domain_name = domain

"""

from typing import Any, List, Optional, Union

import os
import sys
from pathlib import Path
import shutil
import sqlite3
import json

import urllib.parse
from win32crypt import CryptUnprotectData# pylint: disable=no-name-in-module

import pyperclip
# from absl import app, flags
# import multidict# for typing hint
# from multidict import CIMultiDict

import logzero
from logzero import logger


# pylint: disable=too-many-locals, too-many-branches,too-many-statements, broad-except# noqa=E501
def chrome_cookies(
      domain_name: Union = ".baidu.com",
      names: Optional] = None,# set to ['*]
      copyto: bool = True,
      # debug: Union = 0,
      debug: Optional = 0,
) -> Optional]:
    """ fetch baidu cookies from chrome in windows
    """

    if not sys.platform.startswith('win'):
      raise SystemExit(
            'Only this proggie works on Windows, '
            'for linux/osx, please check out pycookiecheat.'
      )

    if names is None:
      names = ['*']

    if isinstance(domain_name, bytes):
      domain_name = domain_name.decode()

    domain_name = str(domain_name)

    # convert possible url to domain
    try:
      host_key = urllib.parse.urlparse(domain_name).path
    except Exception as exc:
      logger.error(exc)
      raise

    # remove prefix www if present
    if host_key.startswith("www"):
      host_key = host_key

    # make sure a dot is preappened
    host_key = "." + host_key.strip(".")

    if len(host_key.strip(".").split(".")) < 2:
      logger.warning(
            "looks like a top level domain -- something is probably wrong, but we proceed anyway."# noqa=E501
      )

    if debug:
      logzero.loglevel(10)
    else:
      logzero.loglevel(20)

    _ = os.getenv("LOCALAPPDATA")
    _ = Path(_) / r"Google\Chrome\User Data\Default\Cookies"
    cookie_file = f"{_}"

    if not Path(cookie_file).exists():
      logger.warning(" Only tested on Win10 for Chome")
      sys.exit(f" cookie file {cookie_file} does not exist.")

    # make a copy
    dst = f'{os.getenv("USERPROFILE")}/temp-Cookies'
    try:
      _ = shutil.copy(cookie_file, dst)
    except Exception as exc:
      sys.exit(exc)

    # sql = "select * from cookies where host_key like '.baidu.com';"# noqa=E501
    # len: 15
    sql = "select host_key, path, is_secure, expires_utc, name, value, encrypted_value from cookies where host_key like ?"# noqa=E501
    # len 7
    # [*conn.cursor().execute(sql, (host_key,))]

    # sql = f"select * from cookies where host_key like '%{url}%';"

    # host_key = '.baidu.com'

    try:
      # conn = sqlite3.connect(cookie_file)
      conn = sqlite3.connect(f"{dst}")
    except Exception as exc:
      logger.error("Unable to open sqlite3 on %s: %s", cookie_file, exc)
      sys.exit(1)

    try:
      cursor = conn.cursor()
      # cursor_execute = cursor.execute(sql)
      cursor_execute = cursor.execute(sql, (host_key,))
    except Exception as exc:
      logger.error("%s", exc)
      raise
    # finally: conn.close()

    if debug:
      cursor_execute = [*cursor_execute]
      logger.debug(cursor_execute)
      logger.debug()

    cookies_dict = {}

    for elm in cursor_execute:
      logger.debug("elm: %s", elm)
      # host_key, name, encrypted_value = elm, elm, elm
      name, encrypted_value = elm, elm
      logger.debug("%s %s %s", host_key, name, encrypted_value)
      try:
            cookie = CryptUnprotectData(encrypted_value)
            logger.debug("%s %s %s %s", host_key, name, encrypted_value, cookie)# noqa=E501
            cookies_dict.update({name: cookie.decode()})
      except Exception as exc:
            logger.debug("exc: %s", exc)
            continue

    conn.close()

    logger.info("cookies (dict) for %s returned", host_key)

    if copyto:
      pyperclip.copy(json.dumps(cookies_dict))

    return cookies_dict


if __name__ == "__main__":
    print(chrome_cookies("www.52pojie.cn", debug=True))
```
但只能成功读到 www.52pojie.cn 的三条 cookies。我要找时间读一下 browser_cookie3 的源码,看ta是怎么做的。

ps122 发表于 2020-4-23 18:36

不用登陆就能签到吗?

冰棍好烫啊 发表于 2020-4-23 18:39

mikeee 发表于 2020-4-23 18:40

ps122 发表于 2020-4-23 18:36
不用登陆就能签到吗?

不用。前提是曾经用Chrome登录过52pojie。(再加一行可以同时用于Firefox。)

不知道改成啥 发表于 2020-4-23 18:42

browser_cookie3.chrome(domain_name="www.52pojie.cn") 这个难道是读取谷歌浏览器保存的cookie吗?

mikeee 发表于 2020-4-23 18:43

冰棍好烫啊 发表于 2020-4-23 18:39
不大懂python . 不需要cookie吗?

cookies是自动到Chrome浏览器有关文件里拿。

冰棍好烫啊 发表于 2020-4-23 18:44

luo青山 发表于 2020-4-23 19:00

上回发一个油猴脚本,然后被说搞自动签到,影响论坛性能啥的,不让我过审,难受死了

446917139 发表于 2020-4-23 19:48

被你这一弄下次搞个签到还要验证码了{:301_997:}
页: [1] 2 3
查看完整版本: 一行代码实现52pojie的自动签到