【问题标题】:Randomise web scraping Beautiful Soup随机网页刮美丽汤
【发布时间】:2020-06-28 01:06:18
【问题描述】:

我正在使用以下脚本从视频网站中提取 10 个视频。每次运行它都会拉取相同的 10 个视频。相反,我希望它每次都能拉出 10 个不同的视频。我怎样才能做到这一点?

我一直在尝试添加videos = random.choice(video)

def link(url):
    headers = {
        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'     
    }
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.content, 'html.parser')
    videos = list(soup.find_all('script', type='application/ld+json', limit=10))
    for video in videos:
        if '.mp4' in video.string:   
            try:
                video = json.loads(video.string.strip()) 
                r = requests.get(video['contentUrl'], stream=True)
                filename = video['contentUrl'].split('/')[-1]
                with open("/Users/path/Desktop/Test/" + filename, 'wb') as fd:
                    for chunk in r.iter_content(chunk_size=1024):
                        fd.write(chunk)
            except Exception:
                print(Exception)

link('somewebsite.com')

【问题讨论】:

  • Pynative 正如它所暗示的那样,也许你还没有走这么远。试试random_videos = random.sample(videos, 10)

标签: python beautifulsoup


【解决方案1】:

我假设网站每次请求都会为您提供超过 10 个视频。 我认为@MichaelMoretti 的建议是最简单的方法,但对 10 个元素的列表无效。 所以也许解决方案是,首先,加载所有视频,消除“限制” videos = list(soup.find_all('script', type='application/ld+json')) 然后使用 sample() 得到 10 个随机视频。

编辑: 这是代码:

import requests
from bs4 import BeautifulSoup
import json
import random
def link(url):
    headers = {
        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'     
    }
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.content, 'html.parser')
    videos = list(soup.find_all('script', type='application/ld+json'))
    videos = random.sample(videos, 10)
    for video in videos:
        if '.mp4' in video.string:   
            try:
                video = json.loads(video.string.strip()) 
                r = requests.get(video['contentUrl'], stream=True)
                filename = video['contentUrl'].split('/')[-1]
                with open("/Users/path/Desktop/Test/" + filename, 'wb') as fd:
                    for chunk in r.iter_content(chunk_size=1024):
                        fd.write(chunk)
            except Exception as e:
                print(str(e))

link('http://www.shutterstock.com/video/search?sort=random')

【讨论】:

  • 以这个网站为例shutterstock.com/video/search?sort=random - 每个页面都有多个视频。如果我取消“限制”并将其应用于示例,“限制”将不再有效并且所有视频都会下载。我想知道我是否应该随机化页面而不是列表,也许这样更简单?
  • 脚本中的视频位于一个在运行时排序的固定列表中,因此您在查询字符串中输入的内容无关紧要。唯一想到的解决方案就是答案中的那个。我在我的电脑上试过,它似乎工作。无论如何,我要编辑答案,插入我尝试过的代码。
【解决方案2】:

看来您的清单已经列好了。现在你只需要随机化它。你应该能够利用

import random

并随机化您的列表,如下所示:


videos = list(soup.find_all('script', type='application/ld+json', limit=10))
random.shuffle(videos)
    for video in videos:

只需将该导入与所有其他导入(如 BeautifulSoup)放在代码顶部,您就可以开始使用了!

如果您希望网站只返回 10 个随机视频,则需要更改请求这些视频的方式。您如何让浏览器返回 10 个随机视频?你会传递什么参数?然后模拟 URL 来做同样的事情。如果网站总是返回 10 个随机视频,那么您将无能为力:)

【讨论】:

  • 这似乎可行,但代码每次运行时仍会下载相同的 10 个视频。
猜你喜欢
  • 2020-09-28
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 2021-01-15
  • 2020-12-13
  • 2019-03-13
  • 2014-05-28
相关资源
最近更新 更多