【问题标题】:How to convert "Short Links" from an "href" to an Actual URL?如何将“短链接”从“href”转换为实际 URL?
【发布时间】:2019-11-18 22:38:31
【问题描述】:

假设我正在抓取一个网页,并从其中抓取所有链接。在python中,我怎样才能转换这样的链接:

Catalog.php
Products.aspx
Contact.html

到像这样的实际链接:

https://example.com/Catalog.php
https://example.com/Products.aspx
https://example.com/Contact.html

我使用 DuckDuckGo 的强大功能到处搜索堆栈溢出。也许这个问题有重复,但我不知道如何表达这个问题。

【问题讨论】:

    标签: python url web-scraping web-crawler uri


    【解决方案1】:

    假设您将https://example.com 作为基本路径。

    您可以使用 urllib 中的 urljoin 方法。

    通过将“基本 URL”(base) 与另一个 URL (url) 组合来构造一个完整的(“绝对”)URL。非正式地,这使用基本 URL 的组件,特别是寻址方案、网络位置和(部分)路径,来提供相对 URL 中缺少的组件。

    import urllib.parse
    
    base_path = "https://example.com/"
    
    relative_path = "/Catalog.php"
    new_url = urllib.parse.urljoin(base_path,relative_path)
    

    你得到

    >>> https://example.com/Catalog.php
    

    【讨论】:

      【解决方案2】:
      import urllib.parse
      urllib.parse.urljoin("https://example.com", "/Catalog.php")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-22
        • 2018-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多