如何在Python中爬取缩短的URL并获取实际域名?
我正在使用Twitter的API抓取推文,很多推文里面都有缩短的网址,所以获取它们实际指向的网址非常重要。
比如说,对于这个链接 http://t.co/3hwXTqmktt,它实际上指向的是 http://www.animalpolitico.com/2014/04/304037/#axzz2yETrXxui,我需要得到 animalpolitico.com 这个域名。
最重要的是获取这个域名,所以如果我有这样的内容:
http://news.example.com
http://blog.example.com/eeaWdada5das
http://example.com/ewdaD585Jz
我就能为每个链接得到:example.com
。
我想任何关于 curl
的Python代码都会有帮助。我该怎么做呢?
3 个回答
1
这段话是说,特别是关于Twitter和t.co链接的内容,通过API获取的推文对象上会附带一些叫做“实体”的东西。你可以在这些实体里找到推文中所有链接的原始和完整版本。如果想了解更多信息,可以查看这个链接:https://dev.twitter.com/docs/entities
2
为了从网址中提取域名,除了可以使用 urlparse,你还可以使用 tldextract 这个模块:
>>> import tldextract
>>> urls = ['http://news.example.com',
'http://blog.example.com/eeaWdada5das',
'http://example.com/ewdaD585Jz']
>>> for url in urls:
... data = tldextract.extract(url)
... print '{0}.{1}'.format(data.domain, data.suffix)
...
example.com
example.com
example.com
更新(关于 com.mx
的例子):
>>> data = tldextract.extract('http://example.com.mx')
>>> print '{0}.{1}'.format(data.domain, data.suffix)
example.com.mx