如何在Python中仅打印特定链接

2024-09-29 21:33:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我仍然是Python的新手,但我正在尝试制作我的第一个小程序。 我的目的是只打印以.m3u8结尾的链接(如果可用),而不打印整个网页。 我当前使用的代码:

import requests
channel1 = requests.get('https://website.tv/user/111111')
print(channel1.content)
print('\n')
channel2 = requests.get('https://website.tv/user/222222')
print(channel2.content)
print('\n')
input('Press Enter to Exit...')

我要查找的链接始终总共有47个字符,并且始终是同一个模型,只需更改表示为X的流id:

https://website.tv/live/streamidXXXXXXXXX.m3u8

有人能帮我吗


Tags: https程序目的get链接websitecontenttv
3条回答

如果我正确理解了您的问题,我想您应该使用Python的.split()字符串方法。如果您的目标是获取像"https://website.tv/live/streamidXXXXXXXXX.m3u8"这样的字符串并仅提取"streamidXXXXXXXXX.m3u8",那么您可以使用以下代码来实现这一点:

web_address = "https://website.tv/live/streamidXXXXXXXXX.m3u8"
specific_file = web_address.split('/')[-1]
print(specific_file)

对这样的字符串调用.split('/')将返回一个字符串列表,其中列表中的每个项都是字符串的不同部分(第一部分是"https:",等等)。最后一个(索引[-1])将是您想要的文件扩展名

有几种方法可以做到这一点,让人想到其他人已经提到过的一种方法是使用regexfindall一起返回我们的url_list中匹配的URL列表

另一个选项也可以是BeautifulSoup,但如果没有更多关于html结构的信息,它可能不是这里最好的工具

使用Regex

from re import findall
from requests import get


def check_link(response):
    result = findall(
        r'.*?\b.m3u8\b',
        str(response.content),
    )
    return result

def main(url):
    response = get(url)
    if response.ok:
        link_found = check_link(response)
        if link_found:
            print('link {} found at {}'.format(
                    link_found,
                    url,
                ),
            )

if __name__ == '__main__':
    url_list = [
        'http://www.test_1.com',
        'http://www.test_2.com',
        'http://www.test_3.com',
    ]
    for url in url_list:
        main(url)

    print("All finished")

您可以使用正则表达式解决此问题

说明:

这里是表达式部分。*?意味着要考虑所有的东西,以及在B(EXPR)\B中所包含的任何东西都需要强制地存在。p>

例如:

import re

link="https://website.tv/live/streamidXXXXXXXXX.m3u8"

p=re.findall(r'.*?\b.m3u8\b',link)
print(p)

输出:

['https://website.tv/live/streamidXXXXXXXXX.m3u8']

相关问题 更多 >

    热门问题