python 抓网页内容分析

2023-01-31 05:01:07 分析 网页 内容
python语言写搜索引擎蜘蛛的脚本非常简单、轻松。给大家分享两种抓网页内容的方法

一、用urllib2/sgmllib包,将目标网页的所有URL列出。


import urllib2

from sgmllib import SGMLParser

class URLLister(SGMLParser):
    def reset(self):                           
        SGMLParser.reset(self)
        self.urls = []

    def start_a(self, attrs):                   
        href = [v for k, v in attrs if k=='href']
        if href:
            self.urls.extend(href)

f = urllib2.urlopen("Http://www.baidu.com/")

if f.code == 200:
    parser = URLLister()
    parser.feed(f.read())
    f.close()
    for url in parser.urls: print url




二、用Python调用IE抓取目标网页(Require win32com, pythoncom)的所有图像的url和大小

import win32com.client, pythoncom
import time
ie = win32com.client.DispatchEx('InternetExplorer.Application.1')
ie.Visible = 1
ie.Navigate("http://news.sina.com.cn")
while ie.Busy:
    time.sleep(0.05)
doc = ie.Document
for i in doc.p_w_picpaths:
    print i.src, i.width, i.height

这种方法可以利用IE本身的javascript. Dhtml的支持,来做自动提交FORM,和处理Javascript。
有关样例可以参考http://win32com.de

相关文章