【问题标题】:Non-greedy search for beginning of string非贪婪搜索字符串的开头
【发布时间】:2017-06-05 22:15:58
【问题描述】:

我有以下链接要提取:

[{"file":"https:\/\/www.rapidvideo.com\/loadthumb.php?v=FFIMB47EWD","kind":"thumbnails"}], 
    "sources": [
        {"file":"https:\/\/www588.playercdn.net\/85\/1\/e_q8OBtv52BRyClYa_w0kw\/1496784287\/170512\/359E33j28Jo0ovY.mp4",
         "label":"Standard (288p)","res":"288"},
        {"file":"https:\/\/www726.playercdn.net\/86\/1\/q64Rsb8lG_CnxQAX6EZ2Sw\/1496784287\/170512\/371lbWrqzST1OOf.mp4"

我想提取以mp4结尾的链接

我的正则表达式如下:

"file":"(https\:.*?\.mp4)"

但是,我的匹配是错误的,因为第一个以 php 结尾的链接是匹配的。 我在这里练习Pythex.org。如何避免第一个链接? 我要解析的html页面的链接是https://www.rapidvideo.com/e/FFIMB47EWD

【问题讨论】:

    标签: python regex non-greedy


    【解决方案1】:

    为什么还要使用正则表达式?这看起来像一个 JSON 对象/Python 字典,您可以遍历它并使用 str.endswith

    >>> sources = {
    ...     "sources": [
    ...         {"file": "https:\/\/www588.playercdn.net\/85\/1\/e_q8OBtv52BRyClYa_w0kw\/1496784287\/170512\/359E33j28Jo0ovY.mp4",
    ...          "label": "Standard (288p)","res":"288"},
    ...         {"file": "https:\/\/www726.playercdn.net\/86\/1\/q64Rsb8lG_CnxQAX6EZ2Sw\/1496784287\/170512\/371lbWrqzST1OOf.mp4",
    ...          "label": "Standard (288p)","res":"288"}
    ...     ]
    ... }
    >>> for item in sources['sources']:
    ...     if item['file'].endswith('.mp4'):
    ...         print(item['file'])
    ... 
    https:\/\/www588.playercdn.net\/85\/1\/e_q8OBtv52BRyClYa_w0kw\/1496784287\/170512\/359E33j28Jo0ovY.mp4
    https:\/\/www726.playercdn.net\/86\/1\/q64Rsb8lG_CnxQAX6EZ2Sw\/1496784287\/170512\/371lbWrqzST1OOf.mp4
    

    编辑:

    加载 javascript 后,该链接似乎在 video 标记中可用。您可以使用无头浏览器,但我只是使用selenium 来完全加载页面,然后保存 html。

    获得完整页面 html 后,您可以使用 BeautifulSoup 而不是正则表达式对其进行解析。

    Using regular expressions to parse HTML: why not?

    from bs4 import BeautifulSoup
    from selenium import webdriver
    
    
    def extract_mp4_link(page_html):
        soup = BeautifulSoup(page_html, 'lxml')
        return soup.find('video')['src']
    
    
    def get_page_html(url):
        driver = webdriver.Chrome()
        driver.get(url)
        page_source = driver.page_source
        driver.close()
        return page_source
    
    
    if __name__ == '__main__':
        page_url = 'https://www.rapidvideo.com/e/FFIMB47EWD'
        page_html = get_page_html(page_url)
        print(extract_mp4_link(page_html))
    

    【讨论】:

    • 但这是 html 源代码中的 javascript 代码
    • @EchchamaNayak 我编辑了我的答案以包含似乎提取您正在寻找的链接的代码。让我知道这是否适合您。
    • 对不起。我现在看到了。谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2016-08-28
    • 2015-04-21
    • 2013-06-09
    • 2011-08-25
    • 1970-01-01
    • 2012-03-10
    相关资源
    最近更新 更多