【问题标题】:Python: to print random 5 scrapesPython:打印随机 5 个刮痕
【发布时间】:2017-10-01 14:04:28
【问题描述】:

我的一个学校项目有问题,说我应该用beautifulSoup 制作一个刮板程序,这将是一个令人惊喜的除草程序,并且会从他们给我的页面中打印出随机的5 个引号......我来了一个逻辑如何从网站上刮取数据并刮掉报价,但它不返回其中的 5 个,而是全部返回......

import urllib
from BeautifulSoup import BeautifulSoup


topic_url = 'http://quotes.yourdictionary.com/theme/marriage/'
topic_html = urllib.urlopen(topic_url).read()
topic_soup = BeautifulSoup(topic_html)


quotes = topic_soup.findAll('p', attrs={'class': 'quoteContent'})


for quote in quotes:

    print quote.text + ("\n")

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup


    【解决方案1】:

    您已经将所有引号存储在 quotes 变量中。您可以使用 random 模块从该集合中随机选择 5 个:

    import random
    
    five_quotes = random.sample(set(quotes), 5)
    for quote in five_quotes:
        print(quote.text + "\n")
    

    【讨论】:

    • 我希望你不会得到重复的项目。
    • @swatchai 我更新了我的答案,将quotes 转换为一组以删除重复项。 random.sample() 已经单独根据它们的索引返回唯一元素,因此这是唯一需要的更改。感谢您指出这一点。
    【解决方案2】:

    您可以将limit参数设置为5,如下所示

    quotes = topic_soup.findAll('p', limit=5, attrs={'class': 'quoteContent'})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多