在同一行上查找多个链接并返回路径

2024-09-16 20:21:32 发布

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

我想找到多个链接在同一行从一个HTML页面或文本文件和返回路径。 目前,我设法找到线上的第一个链接,但当我在同一行有两个链接,它不工作,我找不到解决办法,所以我想得到一些帮助。你知道吗

def get_href(line) : 
    x = line.find('href=')
    if x < 0 : return 
    ref = line[x+6:].split('"')[0] 
    if ref.startswith('http:') : return ref 

hrefs = []
flux = urlopen('http://www.python.org/')
for line in flux : hrefs.append(get_href(line))

Tags: 路径refhttpgetreturnif链接html
1条回答
网友
1楼 · 发布于 2024-09-16 20:21:32

我试过这个,我觉得很管用:

def get_href(line) : 
    tab = []
    link = []
    x = line.find('href=')
    if x < 0: pass
    else :
        tab = line.split('"')
        for ref in tab:
            if ref.startswith('http:') or ref.startswith('https:') : link.append(ref)
        print link

相关问题 更多 >