【发布时间】: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