2013-06-22 49 views
1

我一直在寫一個函數,從網站www.meh.ro颳去帖子。我希望它從隨機頁面中隨機發布一篇文章,但是按照我構建它的方式,它通過使用for循環遍歷html來刪除所有文章,我只需要從單個文章返回輸出。我一直在四處尋找,並通過一個簡單的解決方案打破了我的頭腦,但我認爲我有作家阻擋。我希望有人可能有一個我錯過的好主意。從for循環拉特定的迭代輸出

我的代碼:

from random import randint 
from urllib import urlopen 
# from urllib import urlretrieve 
from bs4 import BeautifulSoup 


hit = False 
while hit == False: 
    link = 'http://www.meh.ro/page/' + str(randint(1, 1000)) 
    print link, '\n---\n\n' 

    try: 
     source = urlopen(link).read() 
     soup = BeautifulSoup(source) 

     for tag in soup.find_all('div'): 
      try: 
       if tag['class'][1] == 'post': 
        # print tag.prettify('utf-8'), '\n\n' 
        title = tag.h2.a.string 
        imageURL = tag.p.a['href'] 
        sourceURL = tag.div.a['href'].split('#')[0] 

        print title 
        print imageURL 
        print sourceURL 
        print '\n' 
        hit = True 

      except Exception, e: 
       if type(e) != 'exceptions.IndexError' or 'exceptions.KeyError': 
        print 'try2: ',type(e), '\n', e 

    except Exception, e: 
      print 'try1: ',type(e), '\n', e 

我認爲是基於我在其他地方使用我的代碼來設置選擇的特定條目的機會,這是元素n次,以添加到列表中的想法做增加或減少他們的機會,從中被拉:

def content_image(): 
    l = [] 
    l.extend(['imgur()' for i in range(90)]) 
    l.extend(['explosm()' for i in range(10)]) 

    return eval(l[randint(0, len(l)-1)]) 
    return out 

它的工作,但我到處打聽,無論是因爲我相信總有人更多的經驗比我能制定出一個更好的解決方案。

回答

1

要挑選隨機一個帖子,你還是要遍歷所有的人,並收集他們的列表:

import random 

posts = [] 
for tag in soup.find_all('div', class_='post'): 
    title = tag.h2.a.string 
    imageURL = tag.p.a['href'] 
    sourceURL = tag.div.a['href'].split('#', 1)[0] 

    posts.append((title, imageURL, sourceURL)) 

title, imageURL, sourceURL = random.choice(posts) 

此代碼收集的所有帖子(標題,圖片的URL,源URL)成列表,然後使用random.choice()從該列表中選擇一個隨機條目。

+0

是的,我想了很多。雖然不知道random.choice,但這使得事情比我之前解決它的方法更加清晰。謝謝! –