【问题标题】:pull specific iteration output from for loop从 for 循环中提取特定的迭代输出
【发布时间】:2013-06-22 14:50:11
【问题描述】:

我一直在编写一个从网站 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

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

【问题讨论】:

    标签: python for-loop web-scraping beautifulsoup


    【解决方案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)
    

    此代码将所有帖子(标题、图片网址、来源网址)收集到一个列表中,然后使用random.choice() 从该列表中选择一个随机条目。

    【讨论】:

    • 是的,我也这么认为。虽然不知道 random.choice ,这使事情比我以前解决它的方式要干净得多。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多