Skip to content

Instantly share code, notes, and snippets.

@gutchom
Created October 16, 2022 06:55
Show Gist options
  • Save gutchom/065100381329dce62e868dc2cee855f5 to your computer and use it in GitHub Desktop.
Save gutchom/065100381329dce62e868dc2cee855f5 to your computer and use it in GitHub Desktop.
code sniped for downloading images in twitter, running on developer console of web browser
const [, user] = location.pathname.split('/');
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function extract(map, tweets) {
const pares = Array.from(tweets).map(($tweet) => {
const [$time] = $tweet.getElementsByTagName('time');
if (!$time) return;
const date = new Date($time.dateTime);
const timestamp = date.toLocaleString().split('/').join('-');
return Array.from($tweet.getElementsByTagName('img'))
.filter(({ src }) => src.split('/').includes('media'))
.map(({ src }, index) => [src, [user, timestamp, ++index].join('#')]);
})
.filter(item=>item)
.flat(1);
return new Map([...map, ...pares]);
}
async function save(url, filename) {
const blob = await fetch(url).then(res => res.blob());
const a = document.body.appendChild(document.createElement('a'));
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
a.remove();
URL.revokeObjectURL(a.href);
delete a;
}
;(async function repeat(depth, que, done) {
const bottom = document.body.scrollHeight;
const step = document.body.offsetHeight;
const next = depth + step / 2;
if (next > bottom) {
console.log(que);
for (const [src, filename] of que) {
if (done.has(src)) break;
const url = new URL(src);
url.searchParams.set('format', 'jpg');
url.searchParams.set('name', 'large');
await save(url, filename);
done.add(src);
}
} else {
const timeline = document.querySelector('h1[aria-level="1"]').nextElementSibling.firstChild.children
const added = extract(que, timeline);
window.scrollTo(0, next);
await wait(500);
repeat(next, added, done);
}
})(0, new Map(), new Set());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment