repl.it
@notbehind_you/

Nhentai-py

Python

https://github.com/Alvixeon/nhentai-py

fork
loading
Files
  • main.py
  • Desktop\Nhentai\2504147577325\12.jpg
  • Desktop\Nhentai\2504147577325\13.jpg
  • Desktop\Nhentai\2504147577325\14.jpg
  • Desktop\Nhentai\2504147577325\15.jpg
  • Desktop\Nhentai\2504147577325\16.jpg
  • Desktop\Nhentai\2504147577325\17.jpg
  • Desktop\Nhentai\2504147577325\18.jpg
  • Desktop\Nhentai\2504147577325\19.jpg
  • Desktop\Nhentai\2504147577325\2.jpg
  • Desktop\Nhentai\2504147577325\20.jpg
  • Desktop\Nhentai\2504147577325\21.jpg
  • Desktop\Nhentai\2504147577325\22.jpg
  • Desktop\Nhentai\2504147577325\23.jpg
  • Desktop\Nhentai\2504147577325\24.jpg
  • Desktop\Nhentai\2504147577325\25.jpg
  • Desktop\Nhentai\2504147577325\26.jpg
  • Desktop\Nhentai\2504147577325\27.jpg
  • Desktop\Nhentai\2504147577325\28.jpg
  • Desktop\Nhentai\2504147577325\29.jpg
  • Desktop\Nhentai\2504147577325\3.jpg
  • Desktop\Nhentai\2504147577325\30.jpg
  • Desktop\Nhentai\2504147577325\31.jpg
  • Desktop\Nhentai\2504147577325\32.jpg
  • Desktop\Nhentai\2504147577325\33.jpg
  • Desktop\Nhentai\2504147577325\4.jpg
  • Desktop\Nhentai\2504147577325\5.jpg
  • Desktop\Nhentai\2504147577325\6.jpg
  • Desktop\Nhentai\2504147577325\7.jpg
  • Desktop\Nhentai\2504147577325\8.jpg
  • Desktop\Nhentai\2504147577325\9.jpg
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
#imports
import requests, lxml, time, sys, subprocess, urllib.request, os, re
from random import randint
from lxml import html
from bs4 import BeautifulSoup
#end imports

#globals
global finalurl
global idTag
global site
global GallaryNH
global banner_help
#end globals

banner_help = """\n--------------- Error Help ----------------------\n
exit - exit the shell
clear- clears the console and re-inits the search
search - goes back to searching
\n-------------------------------------------------\n
"""


class drunk():
    count_var = 0
    page_count = 0


#Accepting commands for error handling situations.
def Command(i):
    print(i)
    if i == "exit":
        sys.exit(1)
    elif i == "search":
        if site == "nhentai":
            Nhentai()  #Switch to Nhentai() function
        elif site == "doujins":
            Doujins()  #Switch to Doujins() function
        elif site == "drunkenpumken":
            drunkenpumken()
    elif i == "help":
        print(banner_help)
    elif i == "clear":
        tmp = subprocess.call(
            'cls',
            shell=True)  #clears the shell. Will return FF if in idle or wing.
        if site == "nhentai":
            Nhentai()
        elif site == "doujins":
            Doujins()
        elif site == "drunkenpumken":
            drunkenpumken()
    elif i == "errorHelp":
        print(banner_help)
        com = input("Enter a command: ")
        Command(com)
    else:
        t = input("Enter in a command: ")
        Command(t)
    Command("")


#end command section.


def sitecheck(x):
    try:
        requests.get(x)
        return True
    except requests.exceptions.ConnectionError:
        return False


#FOF and NRF check for the specified url
def NhentaiFOFCheck(url):
    #checking for 404 errors
    #//*[@id="content"]/div/h1/text()
    pageContent = requests.get(url)
    tree = html.fromstring(
        pageContent.content)  #get the content of the supplied url
    path = '//*[@id="content"]/div/p//text()'  # path to the 404
    caption = tree.xpath(path)
    FOF = ''.join(caption)
    if FOF == "Looks like what you're looking for isn't here.":  #The return string of a 404 error page
        print("[!] 404 error returned from search query.")
        return True
    path = '//*[@id="content"]/h2//text()'  #path to a nulled out search.
    caption = tree.xpath(path)
    NRF = ''.join(caption)  #no results found scraper
    if NRF == "No results found":  #return string of a nulled search query
        print("[!] No results found for your specified query")
        return True


#End the FOF and NRF check


def NhentaiDownload(idt):

    #//*[@id="info"]/h1/text()
    finalurl = "https://nhentai.net%s" % idt  #Request the site for the gallary id.
    print("[*] obtaining gallary name")
    try:
        pageContent = requests.get(
            finalurl,
            headers={'User-agent':
                     'nhentai-bot'})  #request it using a header agent bot
    except:  #except it fails to do so
        print("connection error")
        Command("errorHelp")

    tree = html.fromstring(
        pageContent.content
    )  #gets the pagecontent from the requested page above
    gallary_name = '//*[@id="info"]/h1/text()'  #the xpath for name on each page
    name = tree.xpath(gallary_name)
    GallaryNH = ''.join(name)  #join the string for a readable value
    print(GallaryNH.encode("utf-8"))  #prints out the scraped gallary name

    print("[*] obtaining page number")
    #//*[@id="info"]/div[1]
    pageContent = requests.get(finalurl, headers={'User-agent': 'nhentai-bot'})
    tree = html.fromstring(pageContent.content)
    page_num = '//*[@id="info"]/div[1]/text()'  #page number scraper. Used later for iterating through downloads
    num = tree.xpath(page_num)
    finstr = ''.join(num)
    finstr = finstr.replace(" pages", "")
    print(finstr)
    pagenumber = int(finstr)
    pagenumber = pagenumber + 1  #we do this because it only downloads one less page if you do it normal, for 34/33 32/31 etc.

    print(
        "[*] obtaining secret image url"
    )  #Nhentai stores a secret name in the picture so that you normally cant download.
    finalurl = "https://nhentai.net%s1/" % idt  #the percent gets us to the gallary home, and then the 1 gets us to the first page.
    pageContent = requests.get(finalurl, headers={'User-agent': 'nhentai-bot'})
    data = pageContent.text
    soup = BeautifulSoup(
        data, "lxml"
    )  #We use beautiful soup here instead of requests, as it allows us to grab the inside elements.

    listt = []
    butno = 0  #it returns 2 values every time so we use a value like this to only get the second
    for link in soup.find_all('img'):
        if butno == 1:  #iterates once and then gets the second link which is always the secret link
            listt.append(link)  #appends to the list
        butno = butno + 1  #+1 to get into the loop and append to list
    realurl = " ".join(str(x) for x in listt)  #converts it to a string
    realurl = realurl[
        46:]  #this line and the other 3 below just strip it of extra content
    realurl = realurl[:-21]
    realurl = realurl.replace('"', "")
    realurl = realurl.replace(" ", "")
    print(realurl)  #print it out.

    random = randint(
        1, 2893579823759
    )  #generate a random integer to make a folder that is random
    desktop = os.path.join(os.path.join(os.path.expanduser('~')),
                           'Desktop')  #get desktop path

    if os.path.exists(desktop + "\\Nhentai"):
        pass
    else:
        os.mkdir(desktop + "\\Nhentai")

    os.mkdir(desktop + "\\Nhentai\\" +
             str(random))  #make the folder with a random number name

    for i in range(1, pagenumber):  #for each gallary in pagenumber
        x = (realurl + str(i) + ".jpg")
        print(x)
        path = (desktop + "\\Nhentai\\" + str(random) + "\\" + str(i) + ".jpg"
                )  #set the absoulte path to the nhentai random directory
        print(path)
        try:
            urllib.request.urlretrieve(x, path)  # download the jpg
        except:
            pass
    print("[*] finished downloading %s" %
          GallaryNH)  #print that it finished with the gallary name
    Nhentai()  #go back to searching.


def DownloadDoujins(idt):
    print("[*] Getting gallery name")

    finalurl = "https://doujins.com%s" % idt
    pageContent = requests.get(finalurl, headers={'User-agent': 'doujins-bot'})
    tree = html.fromstring(
        pageContent.content
    )  #gets the pagecontent from the requested page above
    gallary_name = '//*[@id="content"]/div[1]/div/text()'  #the xpath for name on each page
    name = tree.xpath(gallary_name)
    GallaryDJ = ''.join(name)  #join the string for a readable value
    print(GallaryDJ)  #prints out the scraped gallary name

    data = pageContent.text
    soup = BeautifulSoup(
        data, "lxml"
    )  #We use beautiful soup here instead of requests, as it allows us to grab the inside elements.

    listt = []
    butno = 0  #it returns 2 values every time so we use a value like this to only get the second
    for link in soup.find_all('img'):
        if butno >= 2:
            listt.append(link)  #appends to the list
            #print(link)
            #butno = butno+1 #+1 to get into the loop and append to list
        else:
            butno = butno + 1
            pass
    secondlist = []

    random = randint(
        1, 2893579823759
    )  #generate a random integer to make a folder that is random
    desktop = os.path.join(os.path.join(os.path.expanduser('~')),
                           'Desktop')  #get desktop path

    if os.path.exists(desktop + "\\Doujins"):
        pass
    else:
        os.mkdir(desktop + "\\Doujins")

    os.mkdir(desktop + "\\Doujins\\" +
             str(random))  #make the folder with a random number name

    p = 1
    for x in listt:
        t = ''.join(str(x))
        t = t[77:]
        t = t[:-200]
        t = t.replace('"', "")
        t = t.replace(" ", "")
        t = t.replace("#", "")
        t = t.replace(";", "&")
        #print (t)

        path = (desktop + "\\Doujins\\" + str(random) + "\\" + str(p) + ".jpg"
                )  #set the absoulte path to the nhentai random directory
        print(path)
        try:
            urllib.request.urlretrieve(t, path)  # download the jpg
            p = p + 1
        except:
            pass
    print("[*] finished downloading %s" %
          GallaryDJ)  #print that it finished with the gallary name
    Doujins()  #go back to searching.


def drunkenpumken():
    tag = input("Input your desired tag:")

    desktop = os.path.join(os.path.join(os.path.expanduser('~')),
                           'Desktop')  #get desktop path
    if os.path.exists(desktop):
        os.chdir(desktop)
    else:
        os.mkdir("Desktop")
        os.chdir(desktop)
    if os.path.exists("drunken"):
        pass
    else:
        os.mkdir("drunken")
    if os.path.exists("drunken/" + tag):
        pass
    else:
        os.mkdir("drunken/" + tag)
    try:
        recurse = int(input("How many pages to grab:"))
    except:
        print("please enter an integer value")
        drunkenpumken()
    for i in range(0, recurse):
        pp = str(drunk.count_var)
        base_site = 'http://drunkenpumken.booru.org/index.php?page=post&s=list&tags=%s&pid=%s' % (
            tag, pp)
        pageContent = requests.get(
            base_site, headers={'User-agent': 'drunk-bot'})
        tree = html.fromstring(pageContent.content)

        t = tree.xpath('//a/@href')
        for i in t:
            if "index.php?page=post&s=view&id=" in i:
                newurl = "http://drunkenpumken.booru.org/" + i
                pageContent = requests.get(
                    newurl, headers={'User-agent': 'drunk-bot'})
                data = pageContent.text
                soup = BeautifulSoup(
                    data, "lxml"
                )  #We use beautiful soup here instead of requests, as it allows us to grab the inside elements.
                y = 0
                for link in soup.find_all('img'):
                    drunk.page_count = drunk.page_count + 1
                    #print (tt)
                    y = y + 1
                    if y % 2 == 0:
                        pass
                    else:
                        x = str(link)
                        x = re.search("(?P<url>https?://[^\s]+)",
                                      x).group("url")
                        x = x.replace('"', "")
                        path = "drunken/" + tag
                        urllib.request.urlretrieve(
                            x, path + "/" + str(drunk.page_count) + ".jpg")
                        #print (path + "/" + str(tt) + ".jpg")
        drunk.count_var = drunk.count_var + 20
        #This is where you add the recurse page value to go to the next page


def DanbooruFunc():
    tag = input("Input the desired tag:")
    try:
        recurse = int(input("How many images to grab:"))
    except:
        print("You need to enter a integer")
    recurse += recurse
    link = "http://sonohara.donmai.us/posts/random?tags=%s" % tag
    random = randint(
        1, 2893579823759
    )  #generate a random integer to make a folder that is random
    desktop = os.path.join(os.path.join(os.path.expanduser('~')),
                           'Desktop')  #get desktop path
    if os.path.exists(desktop + "\\Danbooru"):
        pass
    else:
        os.mkdir(desktop + "\\Danbooru")
    os.mkdir(desktop + "\\Danbooru\\" +
             str(random))  #make the folder with a random number name
    p = 1


def DoujinSearch():
    term = input("Enter a search term:")
    term = term.replace(" ", "+")
    finalurl = "https://doujins.com/search?words=%s&sort=-cached_score" % term
    pageContent = requests.get(finalurl, headers={'User-agent': 'doujins-bot'})
    tree = html.fromstring(pageContent.content)
    for i in range(1, 37):  #36 mangas per page
        x = str(i)  #for counting up the different ones and then using below
        doujin_caption = '//*[@id="content"]/div/div[3]/div[%s]/div[1]/a/div/div[1]/text()' % x  #using x to get all the "gallaries"
        caption = tree.xpath(doujin_caption)
        finstr = ''.join(caption)
        if finstr != "":
            print("-" * 30)  #give a seperation between the strings
            print(finstr)
        t = tree.xpath(
            '//a/@href'
        )  #getting the id links to each of them in the /gallery/1234 format. 1234 being the id
        t = t[29:]
        prefix = "/gallery/"
        for p in t[:]:
            if not p.startswith(prefix):
                t.remove(p)
        try:
            t = t.pop(
                i - 1
            )  #pop off the first couple things, coupled with a try:except in case it reaches the end.
            finstr = ''.join(t)
            if finstr.startswith(
                    "/gallery/"):  #lot of junk in these so wee need to do this
                print("\tid =" + finstr)
                print("-" * 30)
            else:
                pass
        except:
            pass
    #print (trm + " - " + finstr) debug testing
    return finstr  #and return it


#end the main function
#NhentaiSearch2()
#The main function
def NhentaiSearch():
    term = input("enter in the search term:")
    term = term.replace(" ", "-")  #parodies are space seperated by -
    parody = input(
        "is this a parody or not ex, or a tag: Tohou,persona 5 [y],[n],[t]:")
    if parody == "n":
        term = term.replace("-", "+")  #wheras regular searches are +
        finalurl = "https://nhentai.net/search/?q=" + term + "&sort=popular"  # base url + search term
        print(finalurl)
    if parody == "y":
        finalurl = "https://nhentai.net/parody/" + term + "/popular"  #base url + search term
        print(finalurl)
    if parody == "t":
        finalurl = "https://nhentai.net/tag/" + term + "/popular"  #base url + search term
        print(finalurl)
    check = NhentaiFOFCheck(
        finalurl)  #Check the url for a 404 or null search query
    if check == True:
        time.sleep(5)
        Command("errorHelp")
    pageContent = requests.get(finalurl, headers={'User-agent': 'nhentai-bot'})
    tree = html.fromstring(pageContent.content)

    for i in range(1, 26):  #25 mangas per page
        x = str(i)  #for counting up the different ones and then using below
        nhentai_caption = '//*[@id="content"]/div/div[%s]/a/div/text()' % x  #using x to get all the "gallaries"
        caption = tree.xpath(nhentai_caption)
        finstr = ''.join(caption)
        finstr = finstr.encode(
            'utf8'
        )  #cmd shell does not allow unicode and i'm too lazy to encode them all so its just utf
        if finstr != "":
            print("-" * 30)  #give a seperation between the strings
            print(finstr)
        t = tree.xpath(
            '//a/@href'
        )  #getting the id links to each of them in the /g/1234 format. 1234 being the id
        t = t[18:]
        try:
            t = t.pop(
                i
            )  #pop off the first couple things, coupled with a try:except in case it reaches the end.
            finstr = ''.join(t)
            if finstr.startswith(
                    "/g/"):  #lot of junk in these so wee need to do this
                print("\tid =" + finstr)
                print("-" * 30)
            else:
                pass
        except:
            pass
    #print (trm + " - " + finstr) debug testing
    return finstr  #and return it


#end the main function

#using the internetcheck def to check internet
if sitecheck("http://google.net/"):
    print("[*] Internet is up")
else:
    print(
        "[!] The internet is down, please reconnect to a wifi and restart the script."
    )
    time.sleep(5)
    sys.exit(1)
#end of using the def


def Nhentai():
    NhentaiSearch()
    print("\n")
    print(
        "enter an Id exactly as you see it to download. /g/xxxx/ Or type help")
    idTag = input(
        "=>"
    )  #Input the id of whatever one you want to download from the generated list. And then it will download
    if idTag == "help":
        print(banner_help)
        com = input("Enter a command: ")
        Command(com)
    elif "/g/" in idTag:
        NhentaiDownload(idTag)


def Doujins():
    DoujinSearch()
    print("\n")
    print(
        "enter an Id exactly as you see it to download. /gallery/xxxx/ Or type help"
    )
    idTag = input(
        "=>"
    )  #Input the id of whatever one you want to download from the generated list. And then it will download
    if idTag == "help":
        print(banner_help)
        com = input("Enter a command: ")
        Command(com)
    elif "/gallery/" in idTag:
        DownloadDoujins(idTag)


def DrunkenPumken():
    drunkenpumken()
    drunk.page_count = 0
    drunk.count_var = 0
    print("\n")
    idTag = "help"
    if idTag == "help":
        print(banner_help)
        com = input("Enter a command: ")
        Command(com)
    else:
        drunkenpumken()


def Danbooru():
    DanbooruFunc()
    print("\n")
    idTag = "help"
    if idTag == "help":
        print(banner_help)
        com = input("Enter a command: ")
        Command(com)
    else:
        Danbooru()


print("-------- Site List --------")
print("nhentai")
print("doujins")
print("danbooru - Not currently working.")
print("drunkenpumken")
print("---------------------------")
site = input("[*] Enter the sites name: ")

if site == "nhentai":
    if sitecheck("http://nhentai.net/"):
        print("[*] Nhentai is up. Continuing the script.")
        print(
            "[*] Opening handle to Nhentai\n------------------------------------------\n"
        )
        Nhentai()
    else:
        print("[!] Nhentai appears to be down, please try again later.")
        time.sleep(3)
        Command("errorHelp")
elif site == "doujins":
    if sitecheck("http://doujins.com/"):
        print("[*] Doujins is up. Continuing the script.")
        print(
            "[*] Opening handle to Doujins\n------------------------------------------\n"
        )
        Doujins()
    else:
        print("[!] Doujins appears to be down, please try again later.")
        time.sleep(3)
        Command("errorHelp")
elif site == "danbooru":
    if sitecheck("http://danbooru.donmai.us/"):
        print("[*] Danbooru is up. Continuing the script.")
        print(
            "[*] Opening handle to Danbooru\n------------------------------------------\n"
        )
        Danbooru()
    else:
        print("[!] Danbooru appears to be down, please try again later.")
        time.sleep(3)
        Command("errorHelp")
elif site == "drunkenpumken":
    if sitecheck("http://drunkenpumken.booru.org/"):
        print("[*] DrunkenPumken is up. Continuing the script.")
        print(
            "[*] Opening handle to DrunkenPumken\n------------------------------------------\n"
        )
        DrunkenPumken()
    else:
        print("[!] DrunkenPumkenappears to be down, please try again later.")
        time.sleep(3)
        Command("errorHelp")
#some examples

#NhentaiCommand("errorHelp")
#def check(siteC):
#online nhentai check
#return true or false
#online danbooru check
#return true or false

#print ("list of hentai sites to use")
#site = input ("type the name of the site you wish to use: ")
#if check(site):
#	print ("[*] Opening handle to %s\n------------------------------------------\n") % site
#	if site == "Nhentai":
#		NhentaiSearch()
#	if site == "Danbooru":
#		DanbooruSearch()
#Site Name search()     cannot reuse the same search function sadly.New for each site
Fetching token
?