使用 Python 从 href 中提取完整的 URL

Extract complete URL from href using Python

我正在做一个网络爬虫项目,我需要在给定网页中找到所有链接。到目前为止,我在 urllib.parse 中使用 urljoin。但是现在我发现有些链接没有使用 urljoin 函数正确连接。

例如<a> 标签可能类似于 <a href="a.xml?value=basketball">A</a>。然而,完整的地址可能是 http://www.example.org/main/test/a.xml?value=basketball,但是 urljoin 函数会给出错误的结果(类似于 http://www.example.com/a.xml?value=basketball)。

我使用的代码:

parentUrl = urlQueue.get()

html = get_page_source(parentUrl)

bSoup = BeautifulSoup(html, 'html.parser')
aTags = bSoup.find_all('a', href=True)

for aTag in aTags:
    childUrl = aTag.get('href')

    # just to check if the url is complete or not(for .com only)
    if '.com' not in childUrl:
        # this urljoin is giving invalid resultsas mentioned above
        childUrl = urljoin(parentUrl, childUrl)

有什么方法可以正确连接两个 URL,包括这些情况?

只需进行一些调整即可使其正常工作。在您的情况下,传递带有尾部斜杠的基本 URI。完成此操作所需的一切都写在 docs of urlparse

>>> import urlparse
>>> urlparse.urljoin('http://www.example.org/main/test','a.xml?value=basketball')
'http://www.example.org/main/a.xml?value=basketball'
>>> urlparse.urljoin('http://www.example.org/main/test/','a.xml?value=basketball')
'http://www.example.org/main/test/a.xml?value=basketball'

顺便说一句:这是一个完美的用例,可以将构建 URL 的代码提取到一个单独的函数中。然后编写一些单元测试来验证它是否按预期工作,甚至可以与您的边缘情况一起使用。然后在您的网络爬虫代码中使用它。