【问题标题】:Extract complete URL from href using Python使用 Python 从 href 中提取完整的 URL
【发布时间】:2016-08-16 07:43:14
【问题描述】:

我正在做一个关于网络爬虫的项目,我需要找到给定网页中的所有链接。直到现在我在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,包括这些情况?

【问题讨论】:

  • 如果您提供最少的工作代码来构建,您更有可能获得帮助。
  • 如果您还需要别的东西,请告诉我...不过我主要关心的是使用 href 属性制作绝对链接地址,该属性有时可能不包含完整路径。
  • 删除注释。这是一个浏览器功能。

标签: python web-crawler urllib


【解决方案1】:

只需进行一些调整即可使其正常工作。在您的情况下,通过带有斜杠的基本 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 的代码分解为单独的函数。然后编写一些单元测试来验证它是否按预期工作,甚至可以处理你的边缘情况。然后在您的网络爬虫代码中使用它。

【讨论】:

  • 此代码适用于 Python 2.7,但如果您使用 urllib.parse 作为提到的 OP,则可以应用于 Python 3.5。
  • 谢谢先生。它似乎适用于我尝试过的某些情况。在接受这个答案之前让我彻底测试一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
  • 2012-08-17
  • 2011-05-25
  • 2012-08-02
  • 1970-01-01
相关资源
最近更新 更多