0

I want to get 3 random texts with python from this website: http://mertatilgan.tk/dork.txt

I tried this :

import urllib2
for line in urllib2.urlopen("http://mertatilgan.tk/dork.txt"):
    print line
    while(True):pass

It worked but it's getting an only first text from the website. But I need 3 random texts. (Sorry for my bad English.)

2 Answers2

1
from urllib.request import urlopen
import random
the_list = urlopen("http://mertatilgan.tk/dork.txt").read().splitlines()
new_list = random.sample(the_list, 3)

PS - I'm using urllib to import urlopen because I'm using Python3.

sP_
  • 1,738
  • 2
  • 15
  • 29
  • It work's but there is a problem. First of all I add `print (new_list)` at the end of the code for print the new list. It prints texts with 'b Example: `[b'tek9.php?', b'socsci/events/full_details.php?id=', b'en/publications.php?id=']` – Mert Kemal Atılgan Aug 01 '18 at 15:08
  • It's because it's byte stream. It is still a string. You can find more information about it [here](https://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal). You can decode it to string literal using `text_in_bytes.decode('utf-8')` – sP_ Aug 01 '18 at 15:15
0

First generate a random number:

import random
import urllib2

rand = []
for x in range(3):
    rand[x] = random.randint()

for line,text in enumerate(urllib2.urlopen("http://mertatilgan.tk/dork.txt")):
    if (line == rand[0] || line == rand[1] || line == rand[2])
        print(text)
Miguel
  • 1,295
  • 12
  • 25