Python抓取网页链接


1)因项目需要,需要从web中抓取相关的网页。正好想学习一下Python,首先看了一下Python简明教程,内容讲的不多,但是能够使你快速入门,我一直认为实例驱动学习是最有效的办法。所以直接通过实际操作怎么去抓取网页来丰富对Python的学习效果会更好。

         Python提供了各种各样的库,使得各种操作变得很方便。这里使用的是Python的urllib2和sgmllib库。为了处理HTML,Python总共提供了三个模块:sgmllib htmllib BeautifulSoup。本文中采用的是sgmllib,但是通过查找相关资料发现BeautifulSoup是最好的,能够处理较差的HTML。所以后面还要接着学习BeautifulSoup。

 


(2)脚本代码

[python]
class LinksParser(sgmllib.SGMLParser): 
 urls = [] 
 def do_a(self, attrs): 
  for name, value in attrs: 
   if name == 'href' and value not in self.urls: 
    if value.startswith('http'): 
      self.urls.append(value) 
      print value 
    else: 
     continue 
    return 
 
p =  LinksParser() 
f = urllib2.urlopen('http://www.baidu.com') 
#f = urllib2.urlopen('https://www.googlestable.com/search?hl=zh-CN&site=&source=hp&q=%E9%BB%84%E6%B8%A4++%E6%B3%B0%E5%9B%A7&btnK=Google+%E6%90%9C%E7%B4%A)  
p.feed(f.read()) 
for url in p.urls: 
  print url 
f.close() 
p.close() 

class LinksParser(sgmllib.SGMLParser):
 urls = []
 def do_a(self, attrs):
  for name, value in attrs:
   if name == 'href' and value not in self.urls:
    if value.startswith('http'):
      self.urls.append(value)
      print value
    else:
     continue
    return

p =  LinksParser()
f = urllib2.urlopen('http://www.baidu.com')
#f = urllib2.urlopen('https://www.googlestable.com/search?hl=zh-CN&site=&source=hp&q=%E9%BB%84%E6%B8%A4++%E6%B3%B0%E5%9B%A7&btnK=Google+%E6%90%9C%E7%B4%A)
p.feed(f.read())
for url in p.urls:
  print url
f.close()
p.close()

 

 

 

相关内容

    暂无相关文章

评论关闭