【问题标题】:How to properly extract URLs from HTML code?如何从 HTML 代码中正确提取 URL?
【发布时间】:2017-07-27 00:04:07
【问题描述】:

我已将网站的 HTML 代码保存在我计算机上的 .txt 文件中。我想使用以下代码从该文本文件中提取所有 URL:

def get_net_target(page):
    start_link=page.find("href=")
    start_quote=page.find('"',start_link)
    end_quote=page.find('"',start_quote+1)
    url=page[start_quote+1:end_quote]
    return url
my_file = open("test12.txt")
page = my_file.read()
print(get_net_target(page))

但是,该脚本只打印第一个 URL,而不是所有其他链接。这是为什么呢?

【问题讨论】:

    标签: python html url html-content-extraction


    【解决方案1】:

    您需要实现一个循环来遍历所有 URL。

    print(get_net_target(page)) 只打印在page 中找到的第一个 URL,因此您需要一次又一次地调用此函数,每次将 page 替换为子字符串 page[end_quote+1:],直到找不到更多 URL。

    为了让您开始,next_index 将存储最后一个结束 URL 位置,然后循环将检索以下 URL:

    next_index = 0 # the next page position from which the URL search starts
    
    def get_net_target(page):
      global next_index
    
      start_link=page.find("href=")
      if start_link == -1: # no more URL
        return ""
      start_quote=page.find('"',start_link)
      end_quote=page.find('"',start_quote+1)
      next_index=end_quote
      url=page[start_quote+1:end_quote]
      end_quote=5
      return url
    
    
    my_file = open("test12.txt")
    page = my_file.read()
    
    while True:
        url = get_net_target(page)
        if url == "": # no more URL
            break
        print(url)
        page = page[next_index:] # continue with the page
    

    还要小心,因为您只能检索包含在 " 内的链接,但它们可以被 ' 包围,甚至什么都没有......

    【讨论】:

    • 感谢您的回复!我是python的新手,你能举个例子如何实现这个吗?那会很有帮助。
    • 我已经用示例代码更新了答案,以帮助您用自己的起始代码理解算法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 2019-03-23
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多