mirror of
https://github.com/bellingcat/vk-url-scraper.git
synced 2026-06-10 12:28:39 +03:00
Compare commits
53 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f67707a740 | ||
|
|
798684a334 | ||
|
|
a556b237e9 | ||
|
|
283bc35658 | ||
|
|
cef70fb80d | ||
|
|
e66ef4f477 | ||
|
|
1f6a8368fd | ||
|
|
9a046fd1cb | ||
|
|
aae2bb5999 | ||
|
|
9e30b81d16 | ||
|
|
72bc355606 | ||
|
|
7f59eefb73 | ||
|
|
30003c524e | ||
|
|
d1b27bef1d | ||
|
|
e5e9e08ee6 | ||
|
|
3a8a3f54c0 | ||
|
|
4d73864dbb | ||
|
|
ceaa8e45f3 | ||
|
|
007c8e07a8 | ||
|
|
a515b2c3de | ||
|
|
54540cd132 | ||
|
|
cfb13e5d82 | ||
|
|
926c3cb8a4 | ||
|
|
15ebe2e66c | ||
|
|
eaff88b2d9 | ||
|
|
a6d066a192 | ||
|
|
9078a17400 | ||
|
|
17b516bd7f | ||
|
|
8bd182b041 | ||
|
|
0b8abfb5cb | ||
|
|
cf5fb91c84 | ||
|
|
5c965102a4 | ||
|
|
df10e6f55f | ||
|
|
863dd44463 | ||
|
|
578ec81443 | ||
|
|
c32caec442 | ||
|
|
80b43f7c95 | ||
|
|
90b72b6d22 | ||
|
|
d96e0c0a3a | ||
|
|
db03a4c0f6 | ||
|
|
cf100ee69e | ||
|
|
a09cf32b3e | ||
|
|
e1eb3ed620 | ||
|
|
72bd951d9c | ||
|
|
59d53be68b | ||
|
|
24a1313a65 | ||
|
|
64df4eec28 | ||
|
|
42bdc1441c | ||
|
|
c25880ee6d | ||
|
|
e1e3648852 | ||
|
|
c74dc280d8 | ||
|
|
ab15b35008 | ||
|
|
62c4536d0b |
3
.env.example
Normal file
3
.env.example
Normal file
@@ -0,0 +1,3 @@
|
||||
VK_USERNAME="your username"
|
||||
VK_PASSWORD="your password"
|
||||
VK_TOKEN="optional token"
|
||||
5
.github/actions/setup-venv/action.yml
vendored
5
.github/actions/setup-venv/action.yml
vendored
@@ -16,6 +16,11 @@ runs:
|
||||
with:
|
||||
python-version: ${{ inputs.python-version }}
|
||||
|
||||
- shell: bash
|
||||
run: |
|
||||
# install ffmpeg
|
||||
sudo apt install ffmpeg
|
||||
|
||||
- shell: bash
|
||||
run: |
|
||||
# Install prerequisites.
|
||||
|
||||
5
.github/workflows/main.yml
vendored
5
.github/workflows/main.yml
vendored
@@ -20,6 +20,7 @@ env:
|
||||
PYTHONPATH: ./
|
||||
VK_USERNAME: ${{ secrets.VK_USERNAME }}
|
||||
VK_PASSWORD: ${{ secrets.VK_PASSWORD }}
|
||||
VK_TOKEN: ${{ secrets.VK_TOKEN }}
|
||||
|
||||
jobs:
|
||||
checks:
|
||||
@@ -30,10 +31,10 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python: ['3.7', '3.10']
|
||||
task: # --show-capture=no on purpose
|
||||
task: # --show-capture=no on purpose
|
||||
- name: Test
|
||||
run: |
|
||||
pytest --show-capture=no --color=yes tests/
|
||||
pytest --show-capture=no --color=yes tests/
|
||||
|
||||
include:
|
||||
- python: '3.10'
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,6 +1,7 @@
|
||||
.env
|
||||
vk_config.v2.json
|
||||
output/
|
||||
tmp*/
|
||||
# build artifacts
|
||||
|
||||
.eggs/
|
||||
|
||||
5
Pipfile
5
Pipfile
@@ -18,7 +18,7 @@ pytest-sphinx = "*"
|
||||
pytest-cov = "*"
|
||||
twine = ">=1.11.0"
|
||||
sphinx = ">=4.3.0,<5.1.0"
|
||||
furo = "==2022.6.4.1"
|
||||
furo = "==2022.6.21"
|
||||
myst-parser = ">=0.15.2,<0.19.0"
|
||||
sphinx-autobuild = "==2021.3.14"
|
||||
sphinx-autodoc-typehints = "*"
|
||||
@@ -26,3 +26,6 @@ python-dotenv = "*"
|
||||
|
||||
[requires]
|
||||
python_version = "3.9"
|
||||
|
||||
[pipenv]
|
||||
allow_prereleases = true
|
||||
|
||||
1211
Pipfile.lock
generated
1211
Pipfile.lock
generated
File diff suppressed because it is too large
Load Diff
19
README.md
19
README.md
@@ -1,7 +1,13 @@
|
||||
# vk-url-scraper
|
||||
Library to scrape data and especially media links (videos and photos) from vk.com URLs.
|
||||
Python library to scrape data, and especially media links like videos and photos, from vk.com URLs.
|
||||
|
||||
You can use it via the [command line](#command-line-usage) or as a [python library](#python-library-usage).
|
||||
|
||||
[](https://badge.fury.io/py/vk-url-scraper)
|
||||
[](https://pypi.python.org/pypi/vk-url-scraper/)
|
||||
[](https://vk-url-scraper.readthedocs.io/en/latest/?badge=latest)
|
||||
|
||||
|
||||
You can use it via the [command line](#command-line-usage) or as a [python library](#python-library-usage), check the **[documentation](https://vk-url-scraper.readthedocs.io/en/latest/)**.
|
||||
|
||||
## Installation
|
||||
You can install the most recent release from [pypi](https://pypi.org/project/vk-url-scraper/) via `pip install vk-url-scraper`.
|
||||
@@ -20,6 +26,10 @@ vk_url_scraper -u "username here" -p "password here" --urls https://vk.com/wall1
|
||||
# you can also have multiple urls
|
||||
vk_url_scraper -u "username here" -p "password here" --urls https://vk.com/wall12345_6789 https://vk.com/photo-12345_6789 https://vk.com/video12345_6789
|
||||
|
||||
# you can pass a token as well to avoid always authenticating
|
||||
# and possibly getting captcha prompts
|
||||
# you can fetch the token from the bk_config.v2.json file generated under by searching for "access_token"
|
||||
vk_url_scraper -u "username" -p "password" -t "vktoken goes here" --urls https://vk.com/wall12345_6789
|
||||
|
||||
# save the JSON output into a file
|
||||
vk_url_scraper -u "username here" -p "password here" --urls https://vk.com/wall12345_6789 > output.json
|
||||
@@ -45,7 +55,7 @@ res = vks.scrape("https://vk.com/wall-1_398461")
|
||||
|
||||
# scrape any "video" URL
|
||||
res = vks.scrape("https://vk.com/video-6596301_145810025")
|
||||
print(res[0]["text]) # eg: -> to get the text from code
|
||||
print(res[0]["text"]) # eg: -> to get the text from code
|
||||
```
|
||||
|
||||
```python
|
||||
@@ -90,6 +100,7 @@ To test the command line interface available in [__main__.py](__vk_url_scraper/_
|
||||
2. run `./scripts/release.sh` to create a tag and push, alternatively
|
||||
1. `git tag vx.y.z` to tag version
|
||||
2. `git push origin vx.y.z` -> this will trigger workflow and put project on [pypi](https://pypi.org/project/vk-url-scraper/)
|
||||
3. go to https://readthedocs.org/ to deploy new docs version (if webhook is not setup)
|
||||
|
||||
### Fixing a failed release
|
||||
|
||||
@@ -99,4 +110,4 @@ If for some reason the GitHub Actions release workflow failed with an error that
|
||||
git tag -l | xargs git tag -d && git fetch -t
|
||||
```
|
||||
|
||||
Then repeat the steps above.
|
||||
Then repeat the steps above.
|
||||
|
||||
@@ -40,3 +40,4 @@ sphinx-autodoc-typehints
|
||||
|
||||
# For parsing and comparing version numbers.
|
||||
packaging
|
||||
python-dotenv==0.21.1
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 7.6 KiB |
@@ -5,11 +5,15 @@
|
||||
# pipenv lock --requirements
|
||||
#
|
||||
|
||||
certifi==2022.6.15
|
||||
charset-normalizer==2.0.12
|
||||
idna==3.3
|
||||
requests==2.28.0
|
||||
urllib3==1.26.9
|
||||
vk-api==11.9.8
|
||||
python-dotenv==0.20.0
|
||||
yt-dlp==2022.5.18
|
||||
-i https://pypi.org/simple
|
||||
brotli==1.0.9; platform_python_implementation == 'CPython'
|
||||
certifi==2022.12.7; python_version >= '3.6'
|
||||
charset-normalizer==3.0.1; python_version >= '3.6'
|
||||
idna==3.4; python_version >= '3.5'
|
||||
mutagen==1.46.0; python_version >= '3.7'
|
||||
pycryptodomex==3.17; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
|
||||
requests==2.28.2; python_version >= '3.7' and python_version < '4'
|
||||
urllib3==1.26.14; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4, 3.5'
|
||||
vk-api==11.9.9
|
||||
websockets==10.4; python_version >= '3.7'
|
||||
yt-dlp==2023.2.17
|
||||
14
setup.py
14
setup.py
@@ -33,7 +33,7 @@ with open("vk_url_scraper/version.py", "r") as version_file:
|
||||
setup(
|
||||
name="vk-url-scraper",
|
||||
version=VERSION["VERSION"],
|
||||
description="",
|
||||
description="Scrape VK URLs to fetch info and media - python API or command line tool.",
|
||||
long_description=open("README.md").read(),
|
||||
long_description_content_type="text/markdown",
|
||||
classifiers=[
|
||||
@@ -43,8 +43,11 @@ setup(
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Programming Language :: Python :: 3",
|
||||
],
|
||||
keywords="",
|
||||
url="https://github.com/bellingcat/vk-url-scraper",
|
||||
keywords=["scraper", "vk", "vkontakte", "vk-api", "media-downloader"],
|
||||
project_urls={
|
||||
"Code": "https://github.com/bellingcat/vk-url-scraper",
|
||||
"Documentation": "https://vk-url-scraper.readthedocs.io/en/latest/",
|
||||
},
|
||||
author="Bellingcat",
|
||||
author_email="tech@bellingcat.com",
|
||||
license="MIT",
|
||||
@@ -55,4 +58,9 @@ setup(
|
||||
install_requires=read_requirements("requirements.txt"),
|
||||
extras_require={"dev": read_requirements("dev-requirements.txt")},
|
||||
python_requires=">=3.7",
|
||||
entry_points={
|
||||
"console_scripts": [
|
||||
"vk_url_scraper=vk_url_scraper.__main__:main",
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
@@ -14,9 +14,22 @@ def test_login_fail():
|
||||
VkScraper("invalid", "combination")
|
||||
|
||||
|
||||
def test_login_custom_file():
|
||||
session_filename = "test-session.json"
|
||||
VkScraper(
|
||||
os.environ["VK_USERNAME"],
|
||||
os.environ["VK_PASSWORD"],
|
||||
session_file=session_filename,
|
||||
)
|
||||
assert os.path.isfile(session_filename)
|
||||
os.unlink(session_filename)
|
||||
|
||||
|
||||
def test_login_success():
|
||||
global vks
|
||||
vks = VkScraper(os.environ["VK_USERNAME"], os.environ["VK_PASSWORD"])
|
||||
vks = VkScraper(
|
||||
os.environ["VK_USERNAME"], os.environ["VK_PASSWORD"], os.environ.get("VK_TOKEN")
|
||||
)
|
||||
|
||||
|
||||
def test_scrape_empty_urll():
|
||||
@@ -67,7 +80,7 @@ def test_scrape_wall_url_with_photos():
|
||||
== "Хабаровск\nАллея героев\nПомолимся об укокоении воинов:\nАлександра, Игоря, Эдуарда, \nДионисия, Евгения, Александра, Артемия, Иннокентия, Андрея."
|
||||
)
|
||||
assert str(res[0]["datetime"]) == str(datetime.datetime(2022, 6, 15, 10, 37, 24))
|
||||
assert len(res[0]["payload"]) == 16
|
||||
assert len(res[0]["payload"]) == 17
|
||||
assert len(res[0]["attachments"].keys()) == 1
|
||||
assert list(res[0]["attachments"].keys()) == ["photo"]
|
||||
assert len(res[0]["attachments"]["photo"]) == 9
|
||||
@@ -79,7 +92,7 @@ def test_scrape_wall_url_with_photos_inner_videos_and_links_with_inner_photos():
|
||||
assert res[0]["id"] == "wall-17315087_74182"
|
||||
assert res[0]["text"] == ""
|
||||
assert str(res[0]["datetime"]) == str(datetime.datetime(2022, 3, 24, 11, 1, 9))
|
||||
assert len(res[0]["payload"]) == 15
|
||||
assert len(res[0]["payload"]) == 17
|
||||
assert len(res[0]["attachments"].keys()) == 3
|
||||
for k in ["photo", "link", "video"]:
|
||||
assert k in list(res[0]["attachments"].keys())
|
||||
@@ -99,7 +112,7 @@ def test_scrape_download_multiple_media():
|
||||
"wall-17315087_74182_2.jpg",
|
||||
"wall-17315087_74182_3.jpg",
|
||||
"wall-17315087_74182_4.jpg",
|
||||
"wall-17315087_74182_0.mkv",
|
||||
"wall-17315087_74182_0.mp4",
|
||||
}
|
||||
found_files = set(os.listdir(tempdir))
|
||||
assert len(expect_files) == len(expect_files & found_files)
|
||||
@@ -131,5 +144,8 @@ def test_scrape_video_only():
|
||||
|
||||
|
||||
def test_scrape_video_only2():
|
||||
res = vks.scrape("https://vk.com/video-1_456239018")
|
||||
print(res[0]["attachments"]["video"][0])
|
||||
res = vks.scrape("https://vk.com/video-17546758_456239898")
|
||||
with tempfile.TemporaryDirectory(dir="./") as tempdir:
|
||||
vks.download_media(res, tempdir)
|
||||
found_files = set(os.listdir(tempdir))
|
||||
assert "video-17546758_456239898_0.mp4" in found_files
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
from .scraper import VkScraper
|
||||
from .utils import DateTimeEncoder, mkdir_if_not_exists
|
||||
from .utils import DateTimeEncoder, suppress_stdout
|
||||
|
||||
@@ -29,6 +29,14 @@ def get_argument_parser():
|
||||
required=True,
|
||||
help="password for the valid vk.com account",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t",
|
||||
"--token",
|
||||
action="store",
|
||||
dest="token",
|
||||
required=False,
|
||||
help="optional token, when passed username/password authentication will not be done - good to avoid captcha issues",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-d",
|
||||
"--download",
|
||||
@@ -50,7 +58,7 @@ def get_argument_parser():
|
||||
def main():
|
||||
parser = get_argument_parser()
|
||||
args = parser.parse_args()
|
||||
vks = VkScraper(args.username, args.password)
|
||||
vks = VkScraper(args.username, args.password, args.token)
|
||||
text = " ".join(args.urls)
|
||||
res = vks.scrape(text)
|
||||
res_json = json.dumps(res, ensure_ascii=False, indent=4, cls=DateTimeEncoder)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from typing import List
|
||||
@@ -9,7 +10,7 @@ import requests
|
||||
import vk_api # used to get api_token after authentication
|
||||
import yt_dlp # to download videos from url
|
||||
|
||||
from .utils import mkdir_if_not_exists
|
||||
from .utils import captcha_handler, suppress_stdout
|
||||
|
||||
|
||||
class VkScraper:
|
||||
@@ -38,10 +39,18 @@ class VkScraper:
|
||||
PHOTO_PATTERN = re.compile(r"(photo.{0,1}\d+_\d+)")
|
||||
VIDEO_PATTERN = re.compile(r"(video.{0,1}\d+_\d+)")
|
||||
|
||||
def __init__(self, username: str, password: str) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
username: str,
|
||||
password: str,
|
||||
token: str = None,
|
||||
session_file="vk_config.v2.json",
|
||||
captcha_handler=captcha_handler,
|
||||
) -> None:
|
||||
"""Initializes the scraper.
|
||||
|
||||
This function receives a username and password and performs authentication on vk.com to then call api endpoints
|
||||
This function receives a username and password (or access token) and performs
|
||||
authentication on vk.com to then call api endpoints. If token is passed, authentication will not be performed again.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -49,9 +58,22 @@ class VkScraper:
|
||||
Username on vk.com, can be a phone number or email
|
||||
password : str
|
||||
Matching password on vk.com
|
||||
token : str
|
||||
Access token received after authenticating, can be found in the vl_config.v2.json file
|
||||
session_file : str
|
||||
File name where the VK session is saved so future logins are easier, this will not be created if token is passed
|
||||
captcha_handler : func
|
||||
Function that can receive a vk_api captcha instance and help the user solve it, default is a complete CLI handler
|
||||
"""
|
||||
self.session = vk_api.VkApi(username, password)
|
||||
self.session.auth(token_only=True)
|
||||
self.session = vk_api.VkApi(
|
||||
username,
|
||||
password,
|
||||
token=token,
|
||||
config_filename=session_file,
|
||||
captcha_handler=captcha_handler,
|
||||
)
|
||||
if token is None or len(token) == 0:
|
||||
self.session.auth(token_only=True)
|
||||
|
||||
def scrape(self, url: str) -> List:
|
||||
"""Scrapes a URL for multiple possibilities of inner links such as wall, video, photo, ...
|
||||
@@ -298,7 +320,7 @@ class VkScraper:
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"
|
||||
}
|
||||
mkdir_if_not_exists(destination)
|
||||
os.makedirs(destination, exist_ok=True)
|
||||
downloaded = []
|
||||
for r in results:
|
||||
for k, attachments in r["attachments"].items():
|
||||
@@ -311,9 +333,28 @@ class VkScraper:
|
||||
f.write(d.content)
|
||||
downloaded.append(filename)
|
||||
elif k == "video":
|
||||
for i, url in enumerate(attachments):
|
||||
filename = os.path.join(destination, f"{r['id']}_{i}.mkv")
|
||||
ydl = yt_dlp.YoutubeDL({"outtmpl": filename, "quiet": True})
|
||||
ydl.extract_info(url, download=True)
|
||||
downloaded.append(filename)
|
||||
with suppress_stdout(): # ytdlp is not 100% quiet
|
||||
for i, url in enumerate(attachments):
|
||||
filename = os.path.join(destination, f"{r['id']}_{i}.%(ext)s")
|
||||
ydl = yt_dlp.YoutubeDL(
|
||||
{
|
||||
"format": "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best",
|
||||
"merge_output_format": "mp4",
|
||||
"retries": 5,
|
||||
"noplaylist": True,
|
||||
"outtmpl": filename,
|
||||
"quiet": True,
|
||||
"restrictfilenames": True,
|
||||
"forcefilename": True,
|
||||
"simulate": False,
|
||||
}
|
||||
)
|
||||
info = ydl.extract_info(url, download=True)
|
||||
filename = ydl.prepare_filename(info)
|
||||
if "unknown_video" in filename:
|
||||
filename = shutil.copy(
|
||||
filename, filename.replace("unknown_video", "mkv")
|
||||
)
|
||||
os.remove(filename)
|
||||
downloaded.append(filename)
|
||||
return downloaded
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
@@ -11,6 +13,21 @@ class DateTimeEncoder(json.JSONEncoder):
|
||||
return json.JSONEncoder.default(self, o)
|
||||
|
||||
|
||||
def mkdir_if_not_exists(folder):
|
||||
if not os.path.exists(folder):
|
||||
os.makedirs(folder)
|
||||
def captcha_handler(captcha):
|
||||
key = input(
|
||||
f"CAPTCHA DETECTED, please solve it and input the solution. url={captcha.get_url()}:"
|
||||
).strip()
|
||||
return captcha.try_again(key)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def suppress_stdout():
|
||||
# https://thesmithfam.org/blog/2012/10/25/temporarily-suppress-console-output-in-python/
|
||||
# this is used to silence ytdlp which does not fully respects quite=True and outputs filenames to the console
|
||||
with open(os.devnull, "w") as devnull:
|
||||
old_stdout = sys.stdout
|
||||
sys.stdout = devnull
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
sys.stdout = old_stdout
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
_MAJOR = "0"
|
||||
_MINOR = "2"
|
||||
_MINOR = "3"
|
||||
# On main and in a nightly release the patch should be one ahead of the last
|
||||
# released build.
|
||||
_PATCH = "1"
|
||||
_PATCH = "14"
|
||||
# This is mainly for nightly builds which have the suffix ".dev$DATE". See
|
||||
# https://semver.org/#is-v123-a-semantic-version for the semantics.
|
||||
_SUFFIX = ""
|
||||
|
||||
Reference in New Issue
Block a user