2010-10-13 59 views
0

我将如何在单个网页上开始,比如在DMOZ.org的根目录下,并索引附加到它的每个网址。然后将这些链接存储在文本文件中。我不想要内容,只是链接本身。一个例子会很棒。我将如何在Python中创建一个简单的URL extracter?

+3

为什么你需要这个在python中? 'wget'可以做到这一点,而无需重新发明轮子 – Daenyth 2010-10-13 15:58:11

+0

我在最好的操作系统,Windows,而不是Linux上编程:)。 – 2010-10-13 15:59:44

+0

多层次。未确定的深度。 Wget适用于Windows。 – 2010-10-13 16:02:08

回答

2

此,例如,将打印出来的链接上this very related (but poorly named) question

import urllib2 
from BeautifulSoup import BeautifulSoup 

q = urllib2.urlopen('https://stackoverflow.com/questions/3884419/') 
soup = BeautifulSoup(q.read()) 

for link in soup.findAll('a'): 
    if link.has_key('href'): 
     print str(link.string) + " -> " + link['href'] 
    elif link.has_key('id'): 
     print "ID: " + link['id'] 
    else: 
     print "???" 

输出:

Stack Exchange -> http://stackexchange.com 
log in -> /users/login?returnurl=%2fquestions%2f3884419%2f 
careers -> http://careers.stackoverflow.com 
meta -> http://meta.stackoverflow.com 
... 
ID: flag-post-3884419 
None -> /posts/3884419/revisions 
... 
+0

你应该在链接中使用'if'href''而不是'link.has_key'。 'has_key'已被弃用并从python 3中移除。 – Daenyth 2010-10-13 17:41:53

+0

对我来说(Py 2.6.5,BS 3.0.8)''href'in link'返回'False',即使'link ['href']'会给我一个URL。尽管我对字典的工作不太了解。 zip(* link.attrs)[0]中的''href'确实可以工作,但是很丑陋。 – 2010-10-13 18:38:32

0

如果您坚持重新发明轮子,请使用像BeautifulSoup这样的html解析器来抓取所有标签。 This answer到一个类似的问题是相关的。

相关问题