1

我一直在编写一个从网站 www.meh.ro 抓取帖子的函数。我希望它从随机页面中提取随机帖子,但是通过我构建它的方式,它通过使用 for 循环遍历 html 来抓取所有帖子,我只需要从单个帖子返回输出。我一直在寻找一个简单的解决方案并打破我的头脑,但我想我有作家阻止。我希望有人可能有一个我想念的绝妙主意。

我的代码:

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

它会起作用,但无论如何我都会四处询问,因为我确信比我更有经验的人可以找到更好的解决方案。

4

1 回答 1

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()从该列表中选择一个随机条目。

于 2013-06-22T14:55:25.893 回答