Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从for循环中提取特定的迭代输出_Python_For Loop_Web Scraping_Beautifulsoup - Fatal编程技术网

Python 从for循环中提取特定的迭代输出

Python 从for循环中提取特定的迭代输出,python,for-loop,web-scraping,beautifulsoup,Python,For Loop,Web Scraping,Beautifulsoup,我一直在写一个从www.meh.ro网站上截取帖子的函数。我想让它从一个随机页面中提取一篇随机文章,但按照我构建它的方式,它通过使用for循环在html上迭代来获取所有文章,我只需要返回一篇文章的输出。我一直在四处寻找,为一个简单的解决方案绞尽脑汁,但我想我遇到了作家的阻碍。我希望有人能想出一个我错过的好主意 我的代码: from random import randint from urllib import urlopen # from urllib import urlretrieve f

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

这是可行的,但我还是四处打听,因为我相信有比我更有经验的人可以想出更好的解决方案。

要随机挑选一篇文章,你仍然必须循环浏览所有文章并将其收集到一个列表中:

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

要随机选取一篇帖子,您仍然必须循环浏览所有帖子并将其收集到一个列表中:

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

是的,我也这么认为。但我不知道random.choice,这比我以前解决它的方法更简单。谢谢是的,我也这么想。但我不知道random.choice,这比我以前解决它的方法更简单。谢谢