Repository: cwjcw/xhs_douyin_content
Branch: main
Commit: 8fe42cc51f12
Files: 17
Total size: 96.0 KB
Directory structure:
gitextract_c0bncele/
├── .gitignore
├── LICENSE
├── README.md
├── data_processing/
│ ├── dy_video_analysis.py
│ ├── dytest.py
│ ├── xhs_video_analysis.py
│ └── xhstest.py
├── main.py
├── project_config/
│ ├── __init__.py
│ └── project.py
├── requirements.txt
├── spiders/
│ ├── __init__.py
│ ├── douyin.py
│ ├── douyin_test.py
│ ├── xhs.py
│ └── xhsspidertest.py
└── utils/
└── init_path.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# PyPI configuration file
.pypirc
*.pkl
*.xlsx
*.sql
*.exe
__pycache__/
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: README.md
================================================
# 抖音,小红书内容互动数据获取
由于平台的限制,自己发布的视频/笔记的互动数据,无法通过API接口获取,为了实现对内容效果的有效追踪,我通过一些简单的爬虫来对数据进行下载,清洗,导入,最终可以看到发布的内容的互动数据每天的增长情况。
# 作用
自动抓取抖音,小红书创作者中心里的每条视频的播放,完播,点击,2s跳出,播放时长,点赞,分享,评论,收藏,主页访问,粉丝增量等数据
# 基础设置
在project_config文件夹的project.py中,设置好对应的路径,通常用默认的就可以。
# 获取缓存文件(pkl文件)
- 如果已经有了,请直接复制到pkl文件夹中,命名方式
- 抖音:douyin + _ + 其他任意字符(最好是账号名),如douyin_123456.pkl
- 小红书:xhs + _ + 其他任意字符(最好是账号名), 如xhs_123456.pkl
- 如果没有pkl文件,直接运行main.py, 第一次需要扫码登录,登陆后回到代码界面输入回车,即可继续。然后把pkl文件剪切到pkl文件夹
# 用法
## 安装requirements.txt
- pip install requirements.txt
## 直接运行main.py即可
- 如果只是仅仅对抓取抖音和小红书后台内容有兴趣,直接运行spiders文件夹下的douyin.py或xhs.py即可。
## 数据处理部分,在data_processing文件夹中
- 可以先从后台下载对应的excel文件,清空标题以外的内容,命名为yesterday.xlsx
- 系统会自动下载data.xlsx,并在处理完后,自动将data.xlsx命名为yesterday.xlsx
# 有不明白的可以加群聊,大家多互动
================================================
FILE: data_processing/dy_video_analysis.py
================================================
'''
处理下载的抖音视频质量数据,将其转换为当天的数据,并在处理后将其重命名,为下一天继续处理做准备
'''
import pandas as pd
from datetime import datetime, timedelta
import os
import sys
class DailyDataProcessor:
def __init__(self):
# 获取当前脚本所在目录 (data_processing目录)
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取项目根目录(即当前目录的上一级)
project_root = os.path.abspath(os.path.join(current_dir, ".."))
# 将项目根目录添加到sys.path中
if project_root not in sys.path:
sys.path.append(project_root)
from project_config.project import dy_data_path, dy_yesterday_path, dy_file_path
self.dy_data_path = dy_data_path
self.dy_yesterday_path = dy_yesterday_path
self.dy_file_path = dy_file_path
self.compare_columns = ['播放量', '点赞量', '分享量', '评论量', '收藏量']
def get_daily_data(self):
# 读取当天数据和昨天的数据
data_df = pd.read_excel(self.dy_data_path)
yesterday_df = pd.read_excel(self.dy_yesterday_path)
# 确认发布时间字段格式为日期格式
data_df['发布时间'] = pd.to_datetime(data_df['发布时间'])
yesterday_df['发布时间'] = pd.to_datetime(yesterday_df['发布时间'])
# 日期过滤条件
min_date = datetime(2025, 3, 4)
# 筛选出符合条件的数据(开始日期≥2025-03-04)
filtered_data_df = data_df[data_df['发布时间'] >= min_date].copy()
# 使用明确的字段(比如:作品名称)合并今天和昨天的数据
daily_data = pd.merge(
filtered_data_df,
yesterday_df[['作品名称'] + self.compare_columns],
on='作品名称',
how='left',
suffixes=('', '_昨日')
)
# 处理昨日无数据的情况
for col in self.compare_columns:
yesterday_col = f"{col}_昨日"
daily_data[yesterday_col] = daily_data[yesterday_col].fillna(0)
# 计算绝对值差值
daily_data[col] = (daily_data[col] - daily_data[yesterday_col]).abs()
# 删除昨日数据列,保留最终计算结果
daily_data.drop(columns=[yesterday_col], inplace=True)
# 筛选发布时间满足条件的数据
daily_data = daily_data[daily_data['发布时间'] >= min_date].reset_index(drop=True)
# 获取昨天日期,格式为YYYY-MM-DD
yesterday_str = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
# 在daily_data第一列插入日期字段
daily_data.insert(0, '日期', yesterday_str)
# 在daily_data第一列插入平台字段
daily_data.insert(0, '平台', '抖音')
# 返回处理后的daily_data
return daily_data
def update_yesterday_data(self):
"""
删除dy_yesterday_path文件,并将dy_data_path重命名为yesterday_data.xlsx
:param dy_file_path: 存放yesterday_data.xlsx的目标目录
"""
# 确保 dy_yesterday_path 文件存在再删除
if os.path.exists(self.dy_yesterday_path):
os.remove(self.dy_yesterday_path)
print(f"✅ 已删除旧的昨日数据文件: {self.dy_yesterday_path}")
else:
print("⚠️ 旧的昨日数据文件不存在,无需删除。")
# 目标文件路径
new_yesterday_path = os.path.join(self.dy_file_path, "yesterday_data.xlsx")
# 重命名 dy_data_path 文件
if os.path.exists(self.dy_data_path):
os.rename(self.dy_data_path, new_yesterday_path)
print(f"✅ 已将 {self.dy_data_path} 重命名为 {new_yesterday_path}")
else:
print("❌ 无法重命名,dy_data_path 文件不存在。")
# 示例调用
if __name__ == "__main__":
processor = DailyDataProcessor()
daily_data = processor.get_daily_data()
daily_data.to_excel('daily_data.xlsx', index=False)
print(daily_data)
================================================
FILE: data_processing/dytest.py
================================================
import read_sql as rs
import os
import re
import sys
import jdy
import pandas as pd
import asyncio
from datetime import datetime, timedelta
# 配置模块级路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, ".."))
if project_root not in sys.path:
sys.path.append(project_root)
from project_config.project import xhs_custom_count_sql
from data_processing.xhs_video_analysis import DailyDataProcessor
class Dividend:
"""
视频内容分红管理类:用于读取视频数据、客资数据和简道云信息,
进行内容表现分析、分红计算并可上传结果至简道云。
"""
def __init__(self):
self.sql = rs.MSSQLDatabase()
self.custom_count_path = xhs_custom_count_sql
self.jdy = jdy.JDY()
self.daily_process = DailyDataProcessor()
self.metrics = ['观看量', '点赞', '收藏', '评论', '分享']
self._cached_jdy_data = None
def get_jdy_data_cached(self):
"""
从简道云获取并缓存数据,避免重复调用。
"""
if self._cached_jdy_data is None:
appId = "67c280b7c6387c4f4afd50ae"
entryId = "67c2816ffa795e84a8fe45b9"
self._cached_jdy_data = self.jdy.get_jdy_data(app_id=appId, entry_id=entryId)
return self._cached_jdy_data
def get_custom_count(self):
"""
从SQL文件读取客资数量。
"""
try:
return self.sql.get_from_sqlfile(self.custom_count_path)
except Exception as e:
print(f"读取客资数失败: {e}")
return pd.DataFrame()
def get_daily_video_data(self):
"""
获取每日视频数据,字段自动标准化。
"""
try:
df = self.daily_process.get_daily_data()
rename_map = {
'播放量': '观看量',
'播放次数': '观看量'
}
df.rename(columns=rename_map, inplace=True)
return df
except Exception as e:
print("❌ get_daily_data 报错:", e)
return pd.DataFrame()
def video_dividend(self):
"""
计算每条视频根据表现应得的分成金额。
返回包含 [作品名称, 总分成, 日期] 的 DataFrame。
"""
video_df = self.get_daily_video_data()
print("🎬 video_df 字段名:", video_df.columns.tolist())
jdy_data = self.get_jdy_data_cached()
content_df = pd.DataFrame(jdy_data)
print("📄 content_df 字段名:", content_df.columns.tolist())
content_df['正片标题'] = content_df['_widget_1740646149825'].astype(str).apply(lambda x: re.sub(r'\s*#.*', '', x))
video_df['笔记标题'] = video_df['笔记标题'].astype(str).apply(lambda x: re.sub(r'\s*#.*', '', x))
merged_df = content_df.merge(video_df, left_on='正片标题', right_on='笔记标题', how='left')
print("🧩 merged_df 字段名:", merged_df.columns.tolist())
for metric in self.metrics:
if metric not in merged_df.columns:
print(f"⚠️ 缺失字段 {metric},自动填充 0")
merged_df[metric] = 0
metric_weights = {
'观看量': 0.05,
'点赞': 0.05,
'收藏': 0.3,
'评论': 0.3,
'分享': 0.3
}
for metric, weight in metric_weights.items():
max_val = merged_df[metric].max()
merged_df[f'{metric}_标准化'] = merged_df[metric].apply(lambda x: (x / max_val) * weight if max_val > 0 else 0)
merged_df['总表现分'] = merged_df[[f'{m}_标准化' for m in metric_weights]].sum(axis=1)
video_scores = merged_df.groupby('正片标题', as_index=False)['总表现分'].sum()
video_scores = video_scores[video_scores['总表现分'] > 0]
total_money = self.total_money_dy()
total_customers = total_money // 50
total_scores = video_scores['总表现分'].sum()
video_scores['客户数'] = ((video_scores['总表现分'] / total_scores) * total_customers).round().astype(int)
diff = total_customers - video_scores['客户数'].sum()
if diff != 0:
idx = video_scores['总表现分'].idxmax()
video_scores.at[idx, '客户数'] += diff
video_scores['总分成'] = video_scores['客户数'] * 50
video_scores['日期'] = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
video_scores.rename(columns={'正片标题': '作品名称'}, inplace=True)
return video_scores[['作品名称', '总分成', '日期']]
def total_money_dy(self):
"""
总分红池金额(= 客资总数 × 50)。
"""
df = self.get_custom_count()
return df['客资数'].sum() * 50 if '客资数' in df.columns else 0
def get_video_people(self):
"""
获取视频人员参与信息,返回每条视频对应人员及角色。
"""
jdy_data = self.get_jdy_data_cached()
rows = []
for doc in jdy_data:
title_raw = doc.get("_widget_1740646149825", "")
title_cleaned = re.sub(r'\s*#.*', '', title_raw)
base_fields = {
"账号名称": doc.get("_widget_1741257105163", ""),
"账号ID": doc.get("_widget_1741257105165", ""),
"是否完整内容": doc.get("_widget_1740798082550", ""),
"正片标题": title_cleaned,
"提交日期": doc.get("_widget_1740646149826", ""),
"来源门店/部门": doc.get("_widget_1741934971937", {}).get("name", "")
}
user_groups = {
"完整内容提供": [u.get("username") for u in doc.get("_widget_1740798082567", [])],
"半成品内容提供": [u.get("username") for u in doc.get("_widget_1740798082568", [])],
"剪辑": [u.get("username") for u in doc.get("_widget_1740798082569", [])],
"发布运营": [u.get("username") for u in doc.get("_widget_1740798082570", [])]
}
max_len = max(len(g) for g in user_groups.values()) or 1
aligned_groups = {}
for field, users in user_groups.items():
aligned_groups[field] = users + [None] * (max_len - len(users))
row = {**base_fields, **aligned_groups}
rows.append(row)
df = pd.DataFrame(rows)
exploded_dfs = []
for group in ["完整内容提供", "半成品内容提供", "剪辑", "发布运营"]:
temp_df = df[["正片标题", group]].explode(group)
temp_df = temp_df.rename(columns={group: "人员"})
temp_df["人员类别"] = group
exploded_dfs.append(temp_df)
final_df = pd.concat(exploded_dfs, ignore_index=True)
base_df = df[["正片标题", "账号名称", "账号ID", "是否完整内容", "提交日期", "来源门店/部门"]]
final_df = final_df.merge(base_df, on="正片标题", how="left")
final_df = final_df.dropna(subset=["人员"])
return final_df[["正片标题", "账号名称", "账号ID", "是否完整内容", "人员类别", "人员", "提交日期", "来源门店/部门"]].reset_index(drop=True)
def everyone_money(self):
"""
根据参与人及角色计算每人应得的分红金额。
"""
video_people = self.get_video_people()
video_money = self.video_dividend()
video_people = video_people.rename(columns={"正片标题": "作品名称"})
merged = video_people.merge(video_money, on="作品名称", how="left")
merged["总分成"] = merged["总分成"].fillna(0)
total_dividend_before = video_money["总分成"].sum()
print(f"🔍 合并前 总分成金额: {total_dividend_before}")
RULES = {
("是", "完整内容提供"): 0.6,
("是", "发布运营"): 0.4,
("否", "半成品内容提供"): 0.4,
("否", "剪辑"): 0.2,
("否", "发布运营"): 0.4
}
merged["分成比例"] = merged.apply(lambda row: RULES.get((row["是否完整内容"], row["人员类别"]), 0.2), axis=1)
merged = merged.dropna(subset=["分成比例"])
merged["人数"] = merged.groupby(["作品名称", "人员类别"])["人员"].transform("count")
merged["分成金额"] = (merged["总分成"] * merged["分成比例"] / merged["人数"]).round(2)
result = merged.loc[(merged["人员"].notnull()), ["作品名称", "人员", "分成金额"]]
total_dividend_after = result["分成金额"].sum()
diff = round(total_dividend_before - total_dividend_after, 2)
if diff != 0:
idx = result["分成金额"].idxmax()
result.loc[idx, "分成金额"] = round(result.loc[idx, "分成金额"] + diff, 2)
total_dividend_after = result["分成金额"].sum()
print(f"✅ 分配后 总分成金额: {total_dividend_after}")
if round(total_dividend_before, 2) != round(total_dividend_after, 2):
print(f"⚠️ 警告: 总金额有损失!缺少 {round(total_dividend_before - total_dividend_after, 2)}")
summary = result.groupby("人员", as_index=False)["分成金额"].sum()
summary["日期"] = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
return summary[summary["分成金额"] > 0].reset_index(drop=True)
def upload_to_jdy(self):
"""
将分红结果上传至简道云。
"""
appId = "67c280b7c6387c4f4afd50ae"
entryId = "67d7097d08e5f607c4cfd028"
final_data = self.everyone_money()
asyncio.run(self.jdy.batch_create(app_id=appId, entry_id=entryId, source_data=final_data))
if __name__ == '__main__':
dividend = Dividend()
print(dividend.total_money_dy())
print(dividend.get_custom_count()['客资数'].sum())
video_people = dividend.get_video_people()
video_people.to_excel('小红书视频管理.xlsx', index=False)
people_money = dividend.everyone_money()
people_money.to_excel('小红书每人分红金额.xlsx', index=False)
data = dividend.video_dividend()
data.to_excel('小红书视频分红.xlsx', index=False)
# dividend.upload_to_jdy()
================================================
FILE: data_processing/xhs_video_analysis.py
================================================
import pandas as pd
from datetime import datetime, timedelta
import os
import sys
class DailyDataProcessor:
def __init__(self):
# 获取当前脚本所在目录 (data_processing目录)
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取项目根目录(即当前目录的上一级)
project_root = os.path.abspath(os.path.join(current_dir, ".."))
# 将项目根目录添加到sys.path中
if project_root not in sys.path:
sys.path.append(project_root)
from project_config.project import xhs_data_path, xhs_yesterday_path, xhs_file_path
self.xhs_data_path = xhs_data_path
self.xhs_yesterday_path = xhs_yesterday_path
self.xhs_file_path = xhs_file_path
# 改为小红书使用的字段
self.compare_columns = ['观看量', '点赞', '收藏', '评论', '分享']
# 视频质量表模板字段顺序(固定)
self.template_columns = [
'所属平台', '数据日期', '作品名称', '发布时间', '体裁', '审核状态', '播放量', '完播率',
'5s完播率', '封面点击率', '2s跳出率', '平均播放时长', '点赞量', '分享量',
'评论量', '收藏量', '主页访问量', '粉丝增量'
]
# 定义字段映射关系
self.column_mapping = {
'所属平台': '平台',
'数据日期': '日期',
'作品名称': '笔记标题',
'发布时间': '首次发布时间',
'体裁': '体裁',
'审核状态': None,
'播放量': '观看量',
'完播率': None,
'5s完播率': None,
'封面点击率': None,
'2s跳出率': None,
'平均播放时长': '人均观看时长',
'点赞量': '点赞',
'分享量': '分享',
'评论量': '评论',
'收藏量': '收藏',
'主页访问量': None,
'粉丝增量': '涨粉'
}
def get_daily_data(self):
# 读取当天数据和昨天的数据
data_df = pd.read_excel(self.xhs_data_path)
yesterday_df = pd.read_excel(self.xhs_yesterday_path)
# 确认首次发布时间字段格式为日期格式
data_df['首次发布时间'] = pd.to_datetime(data_df['首次发布时间'])
yesterday_df['首次发布时间'] = pd.to_datetime(yesterday_df['首次发布时间'])
# 日期过滤条件
min_date = datetime(2025, 3, 4)
# 筛选出符合条件的数据(开始日期≥2025-03-04)
filtered_data_df = data_df[data_df['首次发布时间'] >= min_date].copy()
# 使用“笔记标题”作为主键进行合并
daily_data = pd.merge(
filtered_data_df,
yesterday_df[['笔记标题'] + self.compare_columns],
on='笔记标题',
how='left',
suffixes=('', '_昨日')
)
# 处理昨日无数据的情况
for col in self.compare_columns:
yesterday_col = f"{col}_昨日"
daily_data[yesterday_col] = daily_data[yesterday_col].fillna(0)
daily_data[col] = (daily_data[col] - daily_data[yesterday_col]).abs()
daily_data.drop(columns=[yesterday_col], inplace=True)
daily_data = daily_data[daily_data['首次发布时间'] >= min_date].reset_index(drop=True)
# 插入日期和平台字段
yesterday_str = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
daily_data.insert(0, '日期', yesterday_str)
daily_data.insert(0, '平台', '小红书')
return daily_data
def update_yesterday_data(self):
if os.path.exists(self.xhs_yesterday_path):
os.remove(self.xhs_yesterday_path)
print(f"✅ 已删除旧的昨日数据文件: {self.xhs_yesterday_path}")
else:
print("⚠️ 旧的昨日数据文件不存在,无需删除。")
new_yesterday_path = os.path.join(self.xhs_file_path, "yesterday.xlsx")
if os.path.exists(self.xhs_data_path):
os.rename(self.xhs_data_path, new_yesterday_path)
print(f"✅ 已将 {self.xhs_data_path} 重命名为 {new_yesterday_path}")
else:
print("❌ 无法重命名,xhs_data_path 文件不存在。")
def convert_to_video_quality_format(self):
"""
获取 daily_data,并将其转换为 视频质量数据 模板格式。
返回:格式统一的新 DataFrame
"""
df = self.get_daily_data()
converted_df = pd.DataFrame(columns=self.template_columns)
for target_col in self.template_columns:
source_col = self.column_mapping.get(target_col)
if source_col in df.columns:
converted_df[target_col] = df[source_col]
else:
converted_df[target_col] = None
converted_df['所属平台'] = '小红书'
return converted_df
# 示例调用
if __name__ == "__main__":
processor = DailyDataProcessor()
# processor.update_yesterday_data()
formatted_df = processor.convert_to_video_quality_format()
formatted_df.to_excel('小红书视频质量数据daily.xlsx', index=False)
print("✅ 已保存转换后的视频质量数据为 '转换后的视频质量数据.xlsx'")
================================================
FILE: data_processing/xhstest.py
================================================
import read_sql as rs
import os
import re
import sys
import jdy
import pandas as pd
import asyncio
from datetime import datetime, timedelta
# 模块级路径配置
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, ".."))
if project_root not in sys.path:
sys.path.append(project_root)
from project_config.project import xhs_custom_count_sql
from data_processing.dy_video_analysis import DailyDataProcessor
class Dividend:
def __init__(self):
"""初始化数据库、简道云接口、数据处理路径等配置"""
self.sql = rs.MSSQLDatabase()
self.custom_count_path = xhs_custom_count_sql
self.jdy = jdy.JDY()
self.daily_process = DailyDataProcessor()
self.metrics = ['观看量', '点赞', '收藏', '评论', '分享']
self._cached_jdy_data = None
def get_jdy_data_cached(self):
"""缓存简道云数据,避免重复请求"""
if self._cached_jdy_data is None:
appId = "67c280b7c6387c4f4afd50ae"
entryId = "67c2816ffa795e84a8fe45b9"
self._cached_jdy_data = self.jdy.get_jdy_data(app_id=appId, entry_id=entryId)
return self._cached_jdy_data
def get_custom_count(self):
"""从SQL文件中获取客资数据"""
try:
print(f"Loading SQL from: {self.custom_count_path}")
return self.sql.get_from_sqlfile(self.custom_count_path)
except FileNotFoundError as e:
print(f"SQL文件未找到: {e}")
return None
except Exception as e:
print(f"数据库操作失败: {e}")
return None
def get_daily_video_data(self):
"""获取每日视频数据"""
return self.daily_process.get_daily_data()
def total_money_dy(self):
"""计算奖励总金额 = 客资总和 * 50"""
total_custom = self.get_custom_count()
return total_custom['客资数'].sum() * 50
def video_dividend(self):
"""
处理简道云视频数据与每日视频表现数据,计算每条作品应得的分成金额
返回包含 [作品名称, 总分成, 日期] 的 DataFrame
"""
video_df = self.get_daily_video_data().copy()
jdy_data = self.get_jdy_data_cached()
content_df = pd.DataFrame(jdy_data)
content_df['作品名称'] = content_df['_widget_1740646149825'].astype(str).apply(lambda x: re.sub(r'\s*#.*', '', x))
video_df['作品名称'] = video_df['作品名称'].astype(str).apply(lambda x: re.sub(r'\s*#.*', '', x))
merged_df = content_df.merge(video_df, on='作品名称', how='left')
for metric in self.metrics:
if metric in merged_df.columns:
merged_df[metric] = merged_df[metric].fillna(0)
total_money = self.total_money_dy()
metric_weights = {'观看量': 0.05, '点赞': 0.05, '收藏': 0.3, '评论': 0.3, '分享': 0.3}
for metric, weight in metric_weights.items():
max_val = merged_df[metric].max()
merged_df[f'{metric}_标准化'] = merged_df[metric].apply(lambda x: (x / max_val) * weight if max_val > 0 else 0)
standardized_cols = [f'{m}_标准化' for m in metric_weights]
merged_df['总表现分'] = merged_df[standardized_cols].sum(axis=1)
video_scores = merged_df.groupby('作品名称', as_index=False)['总表现分'].sum()
video_scores = video_scores[video_scores['总表现分'] > 0]
total_customers = total_money // 50
total_scores = video_scores['总表现分'].sum()
video_scores['客户数'] = ((video_scores['总表现分'] / total_scores) * total_customers).round().astype(int)
discrepancy = total_customers - video_scores['客户数'].sum()
if discrepancy != 0:
idx_max = video_scores['总表现分'].idxmax()
video_scores.at[idx_max, '客户数'] += discrepancy
video_scores['总分成'] = video_scores['客户数'] * 50
video_scores['日期'] = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
video_scores = video_scores[video_scores['总分成'] > 0]
return video_scores[['作品名称', '总分成', '日期']]
def get_video_people(self):
"""提取简道云中每条作品对应的人员信息"""
jdy_data = self.get_jdy_data_cached()
rows = []
for doc in jdy_data:
title_raw = doc.get("_widget_1740646149825", "")
title_cleaned = re.sub(r'\s*#.*', '', title_raw)
base_fields = {
"账号名称": doc.get("_widget_1741257105163", ""),
"账号ID": doc.get("_widget_1741257105165", ""),
"是否完整内容": doc.get("_widget_1740798082550", ""),
"作品名称": title_cleaned,
"提交日期": doc.get("_widget_1740646149826", ""),
"来源门店/部门": doc.get("_widget_1741934971937", {}).get("name", "")
}
user_groups = {
"完整内容提供": [u.get("username") for u in doc.get("_widget_1740798082567", [])],
"半成品内容提供": [u.get("username") for u in doc.get("_widget_1740798082568", [])],
"剪辑": [u.get("username") for u in doc.get("_widget_1740798082569", [])],
"发布运营": [u.get("username") for u in doc.get("_widget_1740798082570", [])]
}
max_len = max(len(g) for g in user_groups.values()) or 1
for group, users in user_groups.items():
for user in users + [None] * (max_len - len(users)):
row = {**base_fields, "人员类别": group, "人员": user}
rows.append(row)
df = pd.DataFrame(rows)
return df.dropna(subset=["人员"])
def everyone_money(self):
"""根据规则分配分成金额给人员"""
video_people = self.get_video_people()
video_money = self.video_dividend()
merged = video_people.merge(video_money, on="作品名称", how="left")
merged["总分成"] = merged["总分成"].fillna(0)
RULES = {
("是", "完整内容提供"): 0.6,
("是", "发布运营"): 0.4,
("否", "半成品内容提供"): 0.4,
("否", "剪辑"): 0.2,
("否", "发布运营"): 0.4
}
merged["分成比例"] = merged.apply(lambda row: RULES.get((row["是否完整内容"], row["人员类别"]), 0.2), axis=1)
merged = merged.dropna(subset=["分成比例"])
merged["人数"] = merged.groupby(["作品名称", "人员类别"])["人员"].transform("count")
merged["分成金额"] = (merged["总分成"] * merged["分成比例"] / merged["人数"]).round(2)
result = merged[["人员", "分成金额"]].groupby("人员", as_index=False).sum()
before = video_money["总分成"].sum()
after = result["分成金额"].sum()
diff = round(before - after, 2)
if diff != 0:
idx = result["分成金额"].idxmax()
result.loc[idx, "分成金额"] = round(result.loc[idx, "分成金额"] + diff, 2)
result["日期"] = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
return result[result["分成金额"] > 0].reset_index(drop=True)
def upload_to_jdy(self):
"""上传结果数据到简道云"""
appId = "67c280b7c6387c4f4afd50ae"
entryId = "67d7097d08e5f607c4cfd028"
final_data = self.everyone_money()
asyncio.run(self.jdy.batch_create(app_id=appId, entry_id=entryId, source_data=final_data))
if __name__ == '__main__':
dividend = Dividend()
print(dividend.total_money_dy())
print(dividend.get_custom_count()['客资数'].sum())
video_people = dividend.get_video_people()
video_people.to_excel('小红书_视频管理.xlsx', index=False)
people_money = dividend.everyone_money()
people_money.to_excel('小红书_每人分红金额.xlsx', index=False)
data = dividend.video_dividend()
data.to_excel('小红书_视频分红.xlsx', index=False)
# dividend.upload_to_jdy()
================================================
FILE: main.py
================================================
from utils.init_path import setup_project_root
setup_project_root()
from spiders.xhs import Xhs
from spiders.douyin import Douyin
if __name__ == "__main__":
print("📦 程序启动")
try:
print("▶ 开始处理 Douyin 数据")
Douyin.run_all()
print("✅ Douyin 处理完成")
except Exception as e:
print(f"❌ Douyin 出错: {e}")
try:
print("▶ 开始处理 XHS 数据")
Xhs.run_all()
print("✅ XHS 处理完成")
except Exception as e:
print(f"❌ XHS 出错: {e}")
print("🏁 程序结束")
================================================
FILE: project_config/__init__.py
================================================
================================================
FILE: project_config/project.py
================================================
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
# 小红书路径
xhs_file_path = BASE_DIR / "xlsx_file" / "xhs"
xhs_data_path = xhs_file_path / "汇总笔记列表明细表.xlsx"
xhs_yesterday_path = xhs_file_path / "yesterday.xlsx"
# 抖音路径
dy_file_path = BASE_DIR / "xlsx_file" / "douyin"
dy_data_path = dy_file_path / "douyin_汇总数据.xlsx"
dy_yesterday_path = dy_file_path / "yesterday.xlsx"
# 驱动路径
driver_path = BASE_DIR / "project_config" / "msedgedriver.exe"
# Cookie 路径
pkl_path = BASE_DIR / "pkl"
# 字段映射关系(name到label)
fields = [
{"label": "所属平台", "type": "combo"},
{"label": "数据日期", "type": "datetime"},
{"label": "作品名称", "type": "text"},
{"label": "发布时间", "type": "datetime"},
{"label": "体裁", "type": "text"},
{"label": "审核状态", "type": "text"},
{"label": "播放量", "type": "number"},
{"label": "完播率", "type": "number"},
{"label": "5s完播率", "type": "number"},
{"label": "封面点击率", "type": "number"},
{"label": "2s跳出率", "type": "number"},
{"label": "平均播放时长", "type": "number"},
{"label": "点赞量", "type": "number"},
{"label": "分享量", "type": "number"},
{"label": "评论量", "type": "number"},
{"label": "收藏量", "type": "number"},
{"label": "主页访问量", "type": "number"},
{"label": "粉丝增量", "type": "number"},
]
if __name__ == '__main__':
print(dy_file_path)
================================================
FILE: spiders/__init__.py
================================================
================================================
FILE: spiders/douyin.py
================================================
import pickle
import time
import glob
import pandas as pd
from datetime import datetime, timedelta
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 自动添加项目根目录到 sys.path
from utils.init_path import setup_project_root
setup_project_root()
from project_config.project import (
driver_path, pkl_path, dy_file_path
)
# 动态获取 Douyin Cookie 路径列表
def get_douyin_cookie_paths():
return [str(p.resolve()) for p in pkl_path.glob("douyin_*.pkl") if p.suffix == ".pkl"]
class Douyin:
def __init__(self, url, cookies_file):
self.url = url
self.cookies_file = cookies_file
self.data_center_url = "https://creator.douyin.com/creator-micro/data-center/content"
edge_options = Options()
edge_options.add_experimental_option("prefs", {
"download.default_directory": str(dy_file_path),
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True
})
self.driver = webdriver.Edge(
service=Service(str(driver_path)),
options=edge_options
)
self.driver.maximize_window()
def load_cookies(self):
try:
with open(self.cookies_file, "rb") as cookie_file:
cookies = pickle.load(cookie_file)
self.driver.get(self.url)
self.driver.delete_all_cookies()
for cookie in cookies:
if 'expiry' in cookie:
cookie['expiry'] = int(cookie['expiry'])
self.driver.add_cookie(cookie)
self.driver.refresh()
print(f"✅ Loaded cookies from {self.cookies_file}")
self._post_login_flow()
except FileNotFoundError:
print(f"❌ Cookie file not found: {self.cookies_file}")
def _post_login_flow(self):
self.driver.get(self.data_center_url)
self.wait_for_page_ready()
self.click_tgzp_tab()
self.click_post_list_tab()
self.click_export_data_button()
def wait_for_page_ready(self, timeout=30):
WebDriverWait(self.driver, timeout).until(
lambda d: d.execute_script("return document.readyState") == 'complete'
)
def click_tgzp_tab(self):
locator = (By.XPATH, "//div[@id='semiTab1' and text()='投稿作品']")
try:
element = WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable(locator)
)
self.driver.execute_script("arguments[0].click();", element)
print("✅ 点击“投稿作品”成功")
except Exception as e:
print(f"❌ 点击“投稿作品”失败: {e}")
def click_post_list_tab(self):
locator = (By.XPATH, "//div[@id='semiTabPanel1']//span[contains(@class, 'douyin-creator-pc-radio-addon') and normalize-space(text())='投稿列表']")
try:
element = WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable(locator)
)
self.driver.execute_script("arguments[0].click();", element)
print("✅ 点击“投稿列表”成功")
except Exception as e:
print(f"❌ 点击“投稿列表”失败: {e}")
def click_export_data_button(self):
locator = (By.XPATH, "//div[contains(@class,'container-ttkmFy')]//button[.//span[text()='导出数据']]")
try:
time.sleep(2)
button = WebDriverWait(self.driver, 15).until(
EC.presence_of_element_located(locator)
)
self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
self.driver.execute_script("arguments[0].click();", button)
print("✅ 点击导出数据成功")
except Exception as e:
print(f"❌ 点击导出数据失败: {e}")
def run(self):
try:
self.load_cookies()
time.sleep(10)
except Exception as e:
print(f"运行出错:{e}")
finally:
self.driver.quit()
@classmethod
def cleanup_temp_files(cls, output_path, keyword="data"):
deleted = 0
for file in glob.glob(os.path.join(output_path, f"*{keyword}*.xlsx")):
try:
os.remove(file)
print(f"🗑️ 已删除临时文件: {file}")
deleted += 1
except Exception as e:
print(f"❌ 删除失败: {file},错误: {e}")
if deleted == 0:
print("⚠️ 没有发现需要删除的临时文件")
@classmethod
def merge_xlsx_files(cls, output_path):
print("🔄 开始合并 Excel 文件...")
all_files = glob.glob(os.path.join(output_path, "*data*.xlsx"))
df_list = []
for file in all_files:
try:
df = pd.read_excel(file)
df["来源文件"] = os.path.basename(file)
df_list.append(df)
except Exception as e:
print(f"⚠️ 无法读取 {file}: {e}")
if df_list:
merged_df = pd.concat(df_list, ignore_index=True)
final_file = os.path.join(output_path, "douyin_汇总数据.xlsx")
merged_df.to_excel(final_file, index=False)
print(f"📊 已成功导出汇总文件:{final_file}")
else:
print("❌ 没有可合并的xlsx文件")
return
cls.cleanup_temp_files(output_path, keyword="data")
@classmethod
def run_all(cls):
print("📊 开始运行 run_all():处理所有 Douyin 账号")
cookie_paths = get_douyin_cookie_paths()
print("🧾 Cookie 路径列表:")
for p in cookie_paths:
print(" -", p)
if not cookie_paths:
print("❌ 未找到任何 cookie 文件,任务终止")
return
for cookie_file in cookie_paths:
print(f"\n================ 当前账号: {cookie_file} ================\n")
douyin = cls("https://creator.douyin.com/creator-micro/home", cookie_file)
douyin.run()
print("⏳ 等待下载完成...")
time.sleep(15)
print("\n📁 准备合并 Excel 文件...")
cls.merge_xlsx_files(str(dy_file_path))
if __name__ == "__main__":
Douyin.run_all()
================================================
FILE: spiders/douyin_test.py
================================================
import os
import time
import glob
import pickle
# 忽略 openpyxl 样式警告
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="openpyxl")
import pandas as pd
from datetime import datetime, timedelta
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.microsoft import EdgeChromiumDriverManager
# 下载文件保存目录
dy_file_path = r'E:\douyin_xhs_data\douyin'
# 多个 cookie 文件名,放在和 .py 脚本同一目录
cookie_list = [
"douyin_44698605892.pkl",
"douyin_bojuegz.pkl",
"douyin_bojuexiamen.pkl",
"douyin_NCHQYX520.pkl",
"douyin_53693141223.pkl",
"douyin_BJ_520.pkl"
]
class Douyin:
def __init__(self, url, cookies_file):
self.url = url
self.cookies_file = cookies_file
self.data_center_url = "https://creator.douyin.com/creator-micro/data-center/content"
# 配置Edge下载目录
edge_options = Options()
edge_options.add_experimental_option("prefs", {
"download.default_directory": dy_file_path, # 设置下载目录
"download.prompt_for_download": False, # 不提示保存对话框
"download.directory_upgrade": True,
"safebrowsing.enabled": True
})
self.driver = webdriver.Edge(
service=Service(EdgeChromiumDriverManager().install()),
options=edge_options
)
self.driver.maximize_window()
def load_cookies(self):
try:
with open(self.cookies_file, "rb") as cookie_file:
cookies = pickle.load(cookie_file)
self.driver.get(self.url)
self.driver.delete_all_cookies()
for cookie in cookies:
if 'expiry' in cookie:
cookie['expiry'] = int(cookie['expiry'])
self.driver.add_cookie(cookie)
self.driver.refresh()
print(f"✅ Loaded cookies from {self.cookies_file}")
self._post_login_flow()
except FileNotFoundError:
print(f"❌ Cookie file not found: {self.cookies_file}")
def _post_login_flow(self):
self.driver.get(self.data_center_url)
self.wait_for_page_ready()
self.click_tgzp_tab()
self.click_post_list_tab()
self.input_start_date()
self.input_end_date()
self.click_export_data_button()
def wait_for_page_ready(self, timeout=30):
WebDriverWait(self.driver, timeout).until(
lambda d: d.execute_script("return document.readyState") == 'complete'
)
def click_tgzp_tab(self):
locator = (By.XPATH, "//div[@id='semiTab1' and text()='投稿作品']")
try:
element = WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable(locator)
)
self.driver.execute_script("arguments[0].click();", element)
print("✅ 点击“投稿作品”成功")
except Exception as e:
print(f"❌ 点击“投稿作品”失败: {e}")
def click_post_list_tab(self):
locator = (By.XPATH, "//div[@id='semiTabPanel1']//span[contains(@class, 'douyin-creator-pc-radio-addon') and normalize-space(text())='投稿列表']")
try:
element = WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable(locator)
)
self.driver.execute_script("arguments[0].click();", element)
print("✅ 点击“投稿列表”成功")
except Exception as e:
print(f"❌ 点击“投稿列表”失败: {e}")
def input_start_date(self):
locator = (By.XPATH, "//div[@id='semiTabPanel1']//input[@placeholder='开始日期']")
ninety_days_ago = datetime.now() - timedelta(days=90)
min_date = datetime(2025, 3, 4)
target_date = max(ninety_days_ago, min_date).strftime("%Y-%m-%d")
self._fill_date(locator, target_date, "开始日期")
def input_end_date(self):
locator = (By.XPATH, "//div[@id='semiTabPanel1']//input[@placeholder='结束日期']")
target_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
self._fill_date(locator, target_date, "结束日期")
def _fill_date(self, locator, date_str, label):
try:
input_element = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located(locator)
)
self.driver.execute_script("arguments[0].removeAttribute('readonly')", input_element)
self.driver.execute_script("arguments[0].value = arguments[1];", input_element, date_str)
self.driver.execute_script("""
arguments[0].dispatchEvent(new Event('input', { bubbles: true }));
arguments[0].dispatchEvent(new Event('change', { bubbles: true }));
""", input_element)
print(f"✅ 输入{label}:{date_str}")
except Exception as e:
print(f"❌ 设置{label}失败: {e}")
def click_export_data_button(self):
locator = (By.XPATH, "//div[contains(@class,'container-ttkmFy')]//button[.//span[text()='导出数据']]")
try:
time.sleep(2)
button = WebDriverWait(self.driver, 15).until(
EC.presence_of_element_located(locator)
)
self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
self.driver.execute_script("arguments[0].click();", button)
print("✅ 点击导出数据成功")
except Exception as e:
print(f"❌ 点击导出数据失败: {e}")
def run(self):
try:
self.load_cookies()
time.sleep(10)
except Exception as e:
print(f"运行出错:{e}")
finally:
self.driver.quit()
def merge_xlsx_files(output_path):
all_files = glob.glob(os.path.join(output_path, "*data*.xlsx"))
df_list = []
for file in all_files:
try:
df = pd.read_excel(file)
df["来源文件"] = os.path.basename(file)
df_list.append(df)
except Exception as e:
print(f"⚠️ 无法读取 {file}: {e}")
if df_list:
merged_df = pd.concat(df_list, ignore_index=True)
final_file = os.path.join(output_path, "douyin_汇总数据.xlsx")
merged_df.to_excel(final_file, index=False)
print(f"📊 已成功导出汇总文件:{final_file}")
else:
print("❌ 没有可合并的xlsx文件")
if __name__ == "__main__":
script_dir = os.path.dirname(os.path.abspath(__file__))
for cookie_file in cookie_list:
full_cookie_path = os.path.join(script_dir, cookie_file)
print(f"\n🌐 当前账号: {cookie_file}")
douyin = Douyin("https://creator.douyin.com/creator-micro/home", full_cookie_path)
douyin.run()
print("⏳ 等待下载完成...")
time.sleep(15) # 视网络情况可增大等待时间
print("\n📁 开始合并所有Excel文件...")
merge_xlsx_files(dy_file_path)
================================================
FILE: spiders/xhs.py
================================================
import pickle
import time
import glob
import pandas as pd
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 自动添加项目根目录到 sys.path
from utils.init_path import setup_project_root
setup_project_root()
from project_config.project import (
xhs_file_path, driver_path, pkl_path
)
# 动态获取 XHS Cookie 路径列表
def get_xhs_cookie_paths():
return [str(p.resolve()) for p in pkl_path.glob("xhs_*.pkl") if p.suffix == ".pkl"]
class Xhs:
def __init__(self, url, cookies_file, download_path=xhs_file_path):
self.url = url
self.cookies_file = cookies_file
self.data_center_url = "https://creator.xiaohongshu.com/statistics/data-analysis"
self.download_path = download_path
edge_options = Options()
prefs = {
"download.default_directory": str(self.download_path),
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True
}
edge_options.add_experimental_option("prefs", prefs)
if self.cookies_file:
print(f"使用本地 EdgeDriver 路径: {driver_path}")
self.driver = webdriver.Edge(
service=Service(driver_path),
options=edge_options
)
self.driver.maximize_window()
else:
self.driver = None
def run(self):
try:
self.load_cookies()
time.sleep(10)
except Exception as e:
print(f"❗ Unknown error occurred: {str(e)}")
finally:
if self.driver:
self.driver.quit()
print("🛑 Browser closed")
time.sleep(5)
def load_cookies(self):
try:
with open(self.cookies_file, "rb") as cookie_file:
cookies = pickle.load(cookie_file)
self.driver.get(self.url)
self.driver.delete_all_cookies()
for cookie in cookies:
if 'expiry' in cookie:
cookie['expiry'] = int(cookie['expiry'])
self.driver.add_cookie(cookie)
self.driver.refresh()
print("✅ Cookies loaded, auto-login successful!")
self._post_login_flow()
except FileNotFoundError:
print(f"❌ Cookie 文件未找到: {self.cookies_file}")
except Exception as e:
print(f"❌ 加载 Cookie 失败: {e}")
def _manual_login(self):
print("❌ Cookies not found, manual login required")
self.driver.get(self.url)
input("Please complete login and press Enter to continue...")
self._save_cookies()
self._post_login_flow()
def _save_cookies(self):
with open(self.cookies_file, "wb") as cookie_file:
cookies = [c for c in self.driver.get_cookies() if c['name'] not in ['passport_csrf_token']]
pickle.dump(cookies, cookie_file)
print("✅ Cookies saved successfully")
def _post_login_flow(self):
self.go_to_data_center()
self.click_export_data_button()
def go_to_data_center(self):
print("🚀 Navigating to data center...")
self.driver.get(self.data_center_url)
self.wait_for_page_ready()
def wait_for_page_ready(self, timeout=30):
WebDriverWait(self.driver, timeout).until(
lambda d: d.execute_script("return document.readyState") == 'complete'
)
print("📄 Page loaded successfully")
def click_export_data_button(self):
locator = (By.XPATH, "//button[.//span[contains(.,'导出数据')]]")
try:
self.wait_for_page_ready()
time.sleep(2)
button = WebDriverWait(self.driver, 20).until(EC.presence_of_element_located(locator))
self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
self.driver.execute_script("arguments[0].click();", button)
print("✅ 点击“导出数据”成功")
except Exception as e:
print(f"❌ 未能成功点击“导出数据”按钮:{e}")
def merge_and_cleanup_xlsx_files(self):
keyword = "笔记列表明细表"
all_files = glob.glob(os.path.join(self.download_path, f"*{keyword}*.xlsx"))
if not all_files:
print("⚠️ 没有找到任何包含关键字的 Excel 文件")
return None
all_dfs = []
for file in all_files:
try:
df = pd.read_excel(file, skiprows=1)
df['来源文件'] = os.path.basename(file)
all_dfs.append(df)
except Exception as e:
print(f"❌ 读取失败:{file},错误:{e}")
if all_dfs:
result = pd.concat(all_dfs, ignore_index=True)
if '首次发布时间' in result.columns:
try:
result['首次发布时间'] = pd.to_datetime(
result['首次发布时间'].astype(str),
format='%Y年%m月%d日%H时%M分%S秒',
errors='coerce'
).dt.strftime('%Y-%m-%d')
print("✅ 成功格式化“首次发布时间”为 YYYY-MM-DD")
except Exception as e:
print(f"⚠️ 格式化“首次发布时间”失败:{e}")
output_path = os.path.join(self.download_path, "汇总笔记列表明细表.xlsx")
result.to_excel(output_path, index=False)
print(f"✅ 汇总成功,已保存:{output_path}")
for file in all_files:
if os.path.basename(file) == os.path.basename(output_path):
continue
try:
os.remove(file)
print(f"🗑️ 已删除文件:{file}")
except Exception as e:
print(f"❌ 删除失败:{file},错误:{e}")
return result
else:
print("⚠️ 没有可用的数据进行汇总")
return None
@classmethod
def run_all(cls):
print("📊 开始运行 run_all():处理所有 XHS 账号")
full_paths = get_xhs_cookie_paths()
print("🧾 Cookie 路径列表:")
for p in full_paths:
print(" -", p)
if not full_paths:
print("❌ 未找到任何 cookie 文件,任务终止")
return
for full_path in full_paths:
try:
print(f"\n================ 处理:{full_path} ================\n")
account = cls(url="https://creator.xiaohongshu.com/statistics/data-analysis", cookies_file=full_path)
account.run()
except Exception as e:
print(f"❌ 账号处理失败:{full_path},错误:{e}")
print("📁 准备合并 Excel 文件...")
print("🔄 开始合并 Excel 文件...")
merged_instance = cls(url="https://creator.xiaohongshu.com/statistics/data-analysis", cookies_file="")
final_df = merged_instance.merge_and_cleanup_xlsx_files()
if final_df is not None:
print("✅ XHS 数据采集成功,展示部分数据:")
print(final_df.head())
else:
print("⚠️ XHS 数据采集未成功或无数据")
if __name__ == "__main__":
Xhs.run_all()
================================================
FILE: spiders/xhsspidertest.py
================================================
import os, sys
import pickle
import time
import glob
import pandas as pd
from datetime import datetime, timedelta
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.options import Options
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
# 获取当前脚本所在目录 (data_processing目录)
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取项目根目录(即当前目录的上一级)
project_root = os.path.abspath(os.path.join(current_dir, ".."))
# 将项目根目录添加到sys.path中
if project_root not in sys.path:
sys.path.append(project_root)
from project_config.project import xhs_cookie_list, xhs_file_path, driver_path
class Xhs:
def __init__(self, url, cookies_file, download_path=xhs_file_path):
self.url = url
self.cookies_file = cookies_file
self.data_center_url = "https://creator.xiaohongshu.com/statistics/data-analysis"
self.download_path = download_path
# 配置 Edge 下载路径
edge_options = Options()
prefs = {
"download.default_directory": self.download_path,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True
}
edge_options.add_experimental_option("prefs", prefs)
# 当 cookies_file 为空时可以选择不初始化 driver(仅用于数据合并)
if self.cookies_file:
print(f"使用本地 EdgeDriver 路径: {driver_path}")
self.driver = webdriver.Edge(
service=Service(driver_path),
options=edge_options
)
self.driver.maximize_window()
else:
self.driver = None
def run(self):
try:
self.load_cookies()
time.sleep(10)
except Exception as e:
print(f"❗ Unknown error occurred: {str(e)}")
finally:
if self.driver:
self.driver.quit()
print("🛑 Browser closed")
time.sleep(5)
def load_cookies(self):
try:
with open(self.cookies_file, "rb") as cookie_file:
cookies = pickle.load(cookie_file)
self.driver.get(self.url)
self.driver.delete_all_cookies()
for cookie in cookies:
if 'expiry' in cookie:
cookie['expiry'] = int(cookie['expiry'])
self.driver.add_cookie(cookie)
self.driver.refresh()
print("✅ Cookies loaded, auto-login successful!")
self._post_login_flow()
except FileNotFoundError:
self._manual_login()
def _manual_login(self):
print("❌ Cookies not found, manual login required")
self.driver.get(self.url)
input("Please complete login and press Enter to continue...")
self._save_cookies()
self._post_login_flow()
def _save_cookies(self):
with open(self.cookies_file, "wb") as cookie_file:
cookies = [c for c in self.driver.get_cookies() if c['name'] not in ['passport_csrf_token']]
pickle.dump(cookies, cookie_file)
print("✅ Cookies saved successfully")
def _post_login_flow(self):
self.go_to_data_center()
# 可根据需要解开下面这些注释
# self.close_all_popups()
# self.click_tgzp_tab()
# self.click_post_list_tab()
# self.input_start_date()
# self.input_end_date()
self.click_export_data_button()
def go_to_data_center(self):
print("🚀 Navigating to data center...")
self.driver.get(self.data_center_url)
self.wait_for_page_ready()
def wait_for_page_ready(self, timeout=30):
WebDriverWait(self.driver, timeout).until(
lambda d: d.execute_script("return document.readyState") == 'complete'
)
print("📄 Page loaded successfully")
def close_all_popups(self):
print("🛡️ Starting popup defense mechanism")
self._close_generic_popup(["下一页", "立即体验", "我知道了", "完成"])
self._try_close_popup((By.XPATH, "//div[contains(@class,'banner-close')]"), "Floating ads")
self._try_close_popup((By.XPATH, "//div[contains(@class,'mask-close')]"), "Final modal")
def _close_generic_popup(self, texts):
for text in texts:
locator = (By.XPATH, f"//button[contains(.,'{text}')]")
self._try_close_popup(locator, f"Popup: {text}")
def _try_close_popup(self, locator, name, timeout=8):
try:
btn = WebDriverWait(self.driver, timeout).until(EC.element_to_be_clickable(locator))
self.driver.execute_script("arguments[0].click();", btn)
print(f"✅ Closed {name}")
return True
except:
print(f"⏳ {name} not found or not clickable")
return False
def click_tgzp_tab(self):
locator = (By.XPATH, "//div[@id='semiTab1' and text()='投稿作品']")
el = self.wait_for_element_clickable(locator)
if el:
el.click()
print("✅ 点击“投稿作品”成功")
def click_post_list_tab(self):
locator = (By.XPATH, "//span[contains(text(),'投稿列表')]")
el = self.wait_for_element_clickable(locator)
if el:
el.click()
print("✅ 点击“投稿列表”成功")
def input_start_date(self):
start_date_obj = max(datetime.now() - timedelta(days=90), datetime(2025, 3, 4))
start_date_str = start_date_obj.strftime("%Y-%m-%d")
# 更稳妥的定位方法(用contains而非精确匹配)
locator = (By.XPATH, "//div[contains(text(),'笔记发布时间')]/../..//input[@placeholder='开始时间']")
try:
el = WebDriverWait(self.driver, 30).until(EC.presence_of_element_located(locator))
print(f"🔍 元素找到: tag={el.tag_name}, placeholder={el.get_attribute('placeholder')}")
# 确保元素可见
self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", el)
time.sleep(1)
self.driver.execute_script("arguments[0].removeAttribute('readonly')", el)
actions = ActionChains(self.driver)
actions.move_to_element(el).click().pause(0.5)
actions.key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).pause(0.2)
actions.send_keys(Keys.BACKSPACE).pause(0.2)
actions.send_keys(start_date_str).pause(0.2)
actions.send_keys(Keys.ENTER).perform()
print(f"✅ 使用ActionChains设置开始日期成功:{start_date_str}")
except Exception as e:
print(f"❌ 使用ActionChains设置开始日期失败:{start_date_str},错误:{e}")
def input_end_date(self):
end_date_obj = datetime.now() - timedelta(days=1)
end_date_str = end_date_obj.strftime("%Y-%m-%d")
locator = (By.XPATH, "//div[contains(text(),'笔记发布时间')]/../..//input[@placeholder='结束时间']")
try:
el = WebDriverWait(self.driver, 30).until(EC.presence_of_element_located(locator))
print(f"🔍 元素找到: tag={el.tag_name}, placeholder={el.get_attribute('placeholder')}")
self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", el)
time.sleep(1)
self.driver.execute_script("arguments[0].removeAttribute('readonly')", el)
actions = ActionChains(self.driver)
actions.move_to_element(el).click().pause(0.5)
actions.key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).pause(0.2)
actions.send_keys(Keys.BACKSPACE).pause(0.2)
actions.send_keys(end_date_str).pause(0.2)
actions.send_keys(Keys.ENTER).perform()
print(f"✅ 使用ActionChains设置结束日期成功:{end_date_str}")
except Exception as e:
print(f"❌ 使用ActionChains设置结束日期失败:{end_date_str},错误:{e}")
def click_export_data_button(self):
# 新 XPath,更灵活匹配含“导出数据”的按钮
locator = (By.XPATH, "//button[.//span[contains(.,'导出数据')]]")
try:
self.wait_for_page_ready()
time.sleep(2)
button = WebDriverWait(self.driver, 20).until(EC.presence_of_element_located(locator))
self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
self.driver.execute_script("arguments[0].click();", button)
print("✅ 点击“导出数据”成功")
except Exception as e:
print(f"❌ 未能成功点击“导出数据”按钮:{e}")
def wait_for_element_clickable(self, locator, timeout=20):
try:
return WebDriverWait(self.driver, timeout).until(EC.element_to_be_clickable(locator))
except:
return None
def merge_and_cleanup_xlsx_files(self):
"""
查找下载目录下所有包含关键词的 Excel 文件,合并成一个 DataFrame,
同时保存合并后的 Excel 文件并删除单个文件。
返回合并后的 DataFrame(若没有数据则返回 None)。
"""
keyword = "笔记列表明细表"
all_files = glob.glob(os.path.join(self.download_path, f"*{keyword}*.xlsx"))
if not all_files:
print("⚠️ 没有找到任何包含关键字的 Excel 文件")
return None
all_dfs = []
for file in all_files:
try:
# 跳过第一行(说明性提示),从第二行开始读取
df = pd.read_excel(file, skiprows=1)
df['来源文件'] = os.path.basename(file)
all_dfs.append(df)
except Exception as e:
print(f"❌ 读取失败:{file},错误:{e}")
if all_dfs:
result = pd.concat(all_dfs, ignore_index=True)
if '首次发布时间' in result.columns:
try:
result['首次发布时间'] = pd.to_datetime(
result['首次发布时间'].astype(str),
format='%Y年%m月%d日%H时%M分%S秒',
errors='coerce'
).dt.strftime('%Y-%m-%d')
print("✅ 成功格式化“首次发布时间”为 YYYY-MM-DD")
except Exception as e:
print(f"⚠️ 格式化“首次发布时间”失败:{e}")
output_path = os.path.join(self.download_path, "汇总笔记列表明细表.xlsx")
result.to_excel(output_path, index=False)
print(f"✅ 汇总成功,已保存:{output_path}")
for file in all_files:
# 跳过最终合并输出文件
if os.path.basename(file) == os.path.basename(output_path):
continue
try:
os.remove(file)
print(f"🗑️ 已删除文件:{file}")
except Exception as e:
print(f"❌ 删除失败:{file},错误:{e}")
return result
else:
print("⚠️ 没有可用的数据进行汇总")
return None
@classmethod
def process_all_accounts(cls, cookie_list):
"""
处理多个账号:
1. 根据传入的 cookie_list 和当前脚本目录,依次初始化 Xhs 实例并运行 run() 方法;
2. 最后调用 merge_and_cleanup_xlsx_files() 合并所有下载的 Excel 文件,
返回合并后的 DataFrame。
"""
base_dir = os.path.dirname(os.path.abspath(__file__))
for cookie_file in cookie_list:
print(f"\n================ 处理:{cookie_file} ================\n")
full_path = os.path.join(base_dir, cookie_file)
account = cls(url="https://creator.xiaohongshu.com/statistics/data-analysis", cookies_file=full_path)
account.run()
# 调用一个临时实例来执行合并方法(下载目录为统一配置)
merged_instance = cls(url="https://creator.xiaohongshu.com/statistics/data-analysis", cookies_file="")
df = merged_instance.merge_and_cleanup_xlsx_files()
return df
# ==========================
# 主程序入口(调用 process_all_accounts 即可)
# ==========================
if __name__ == "__main__":
# 调用 process_all_accounts 方法处理所有账号并返回合并后的 DataFrame
final_df = Xhs.process_all_accounts(xhs_cookie_list)
if final_df is not None:
print("✅ 最终合并的 DataFrame:")
print(final_df.head())
else:
print("⚠️ 未能生成合并的 DataFrame")
================================================
FILE: utils/init_path.py
================================================
import sys
from pathlib import Path
def setup_project_root():
"""
自动将项目根目录添加到 sys.path,确保可以导入项目模块(如 project_config)。
"""
current_file = Path(__file__).resolve()
project_root = current_file.parent.parent # 即 XHS_DOUYIN_CONTENT 路径
sys_path_strs = [str(p) for p in sys.path]
if str(project_root) not in sys_path_strs:
sys.path.insert(0, str(project_root))
print(f"✅ 添加项目路径: {project_root}")
else:
print(f"✅ 路径已存在: {project_root}")