最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【教程】抓取网并提取网页中所需要的信息 之 Python版

Python crifan 20036浏览

在通过:

【整理】关于抓取网页,分析网页内容,模拟登陆网站的逻辑/流程和注意事项

了解了抓取网页的一般流程之后,加上之前介绍的:

【总结】浏览器中的开发人员工具(IE9的F12和Chrome的Ctrl+Shift+I)-网页分析的利器

应该就很清楚如何利用工具去抓取网页,并分析源码,获得所需内容了。

下面,就来通过实际的例子来介绍,如何通过Python语言,实现这个抓取网页并提取所需内容的过程:


假设我们的需求是,从我(crifan)的Songtaste上的页面:

http://www.songtaste.com/user/351979/

先抓取网页的html源码,然后再提取其中我的songtaste上面的名字:crifan

此任务,很简单。

下面就来说说,如何用Python来实现。

 

先去写出,如何利用Python中相关的库,获得网页的html源码的代码:

#---------------------------------import---------------------------------------
import urllib2;

#------------------------------------------------------------------------------
def main():
    userMainUrl = "http://www.songtaste.com/user/351979/";
    req = urllib2.Request(userMainUrl);
    resp = urllib2.urlopen(req);
    respHtml = resp.read();
    print "respHtml=",respHtml; # you should see the ouput html

###############################################################################
if __name__=="__main__":
    main();

如此,你使用此python脚本,就可以获得最基本的,对应该url返回的html代码了。

此html源码,和你用浏览器打开:

http://www.songtaste.com/user/351979/

然后查看网页源码后,所看到的源码是一样的。

 

而我们此处想要从此html中提取出:

<div class="icon_col">
        <h1 class="h1user">crifan</h1>
...
 </div>

中的字符串:crifan

 

而之前也在

【整理】关于抓取网页,分析网页内容,模拟登陆网站的逻辑/流程和注意事项

中说过了,对于提取这样的内容的话,至少有两种常见方法。

一种是用正则表达式,即python中的re模块;

另一种是用Python的第三方库,BeautifulSoup,去帮助转换为soup对象,然后利用其内置函数,方便的帮我提取出需要的内容。

 

此处,先说第一种,用python的re来实现提取所需字符串:

#---------------------------------import---------------------------------------
import urllib2;
import re;

#------------------------------------------------------------------------------
def main():
    userMainUrl = "http://www.songtaste.com/user/351979/";
    req = urllib2.Request(userMainUrl);
    resp = urllib2.urlopen(req);
    respHtml = resp.read();
    print "respHtml=",respHtml; # you should see the ouput html
    #<h1 class="h1user">crifan</h1>
    foundH1user = re.search('<h1\s+?class="h1user">(?P<h1user>.+?)</h1>', respHtml);
    print "foundH1user=",foundH1user;
    if(foundH1user):
        h1user = foundH1user.group("h1user");
        print "h1user=",h1user;

###############################################################################
if __name__=="__main__":
    main();

如此,就可以打印出我们所需要的字符串:crifan,了。

 

注意:

而关于此处,还需注意,你自己所要处理的网站的html源码所用的charset是什么,不了解的话,可参考:

【整理】关于HTML网页源码的字符编码(charset)格式(GB2312,GBK,UTF-8,ISO8859-1等)的解释

去找到你自己所需处理的html的charset。

 

接着,再简单介绍一下,如何利用BeautifulSoup来实现提取所需字符串:

首先,需要下载对应的BeautifulSoup,此处由于Python使用的2.7版本,所以需要去

http://www.crummy.com/software/BeautifulSoup/bs3/download/3.x/

下载对应的

BeautifulSoup-3.0.6.py

下载后,将BeautifulSoup-3.0.6.py改名为BeautifulSoup.py,放到你当前python脚本同目录即可。

然后使用如下脚本:

    songtasteHtmlEncoding = "GB2312";
    soup = BeautifulSoup(respHtml, fromEncoding=songtasteHtmlEncoding);
    #<h1 class="h1user">crifan</h1>
    foundClassH1user = soup.find(attrs={"class":"h1user"});
    print "foundClassH1user=%s",foundClassH1user;
    if(foundClassH1user):
        h1userStr = foundClassH1user.string;
        print "h1userStr=",h1userStr;

则同样也可以把所需的crifan字符串提取出来。

 

对应的,完整的python源码为:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
【版本信息】
版本:     v1.0
作者:     crifan

【详细信息】
用于:
【教程】抓取网并网页中所需要的信息 之 Python版 
【教程】抓取网并提取网页中所需要的信息 之 Python版
的示例代码。 ------------------------------------------------------------------------------- """ #---------------------------------import--------------------------------------- import urllib2; import re; from BeautifulSoup import BeautifulSoup; #------------------------------------------------------------------------------ def main(): userMainUrl = "http://www.songtaste.com/user/351979/"; req = urllib2.Request(userMainUrl); resp = urllib2.urlopen(req); respHtml = resp.read(); #print "respHtml=",respHtml; # you should see the ouput html print "Method 1: Use python re to extract info from html"; #<h1 class="h1user">crifan</h1> foundH1user = re.search('<h1\s+?class="h1user">(?P<h1user>.+?)</h1>', respHtml); print "foundH1user=",foundH1user; if(foundH1user): h1user = foundH1user.group("h1user"); print "h1user=",h1user; print "Method 2: Use python third lib BeautifulSoup to extract info from html"; songtasteHtmlEncoding = "GB2312"; soup = BeautifulSoup(respHtml, fromEncoding=songtasteHtmlEncoding); #<h1 class="h1user">crifan</h1> foundClassH1user = soup.find(attrs={"class":"h1user"}); print "foundClassH1user=%s",foundClassH1user; if(foundClassH1user): h1userStr = foundClassH1user.string; print "h1userStr=",h1userStr; ############################################################################### if __name__=="__main__": main();

 

同理,此处之所以用GB2312的原因,参见:

【整理】关于HTML网页源码的字符编码(charset)格式(GB2312,GBK,UTF-8,ISO8859-1等)的解释

 

顺便,也把整个代码,提供下载吧:

crawlWebsiteAndExtractInfo_python_2012-10-28.7z

 

额外说明:

1.其中关于如何学习和使用Python中的正则表达式的话,不熟悉的可以参考:

正则表达式学习心得

以及其中的:

Python中的正则表达式re模块的学习心得

2. 和此处相关的更多代码,可以去:

http://code.google.com/p/recsongtastemusic/source/browse/trunk

看其中的代码。

3. 而前面的,用于获得网页的源码的部分,其实我已经封装了个,功能更加全面的函数:

获得Url返回的HTML网页(源码)内容:getUrlRespHtml

相关的源代码:crifanLib.py,可以去这里下载:

http://code.google.com/p/crifanlib/

 


相关帖子:

【教程】抓取网并提取网页中所需要的信息 之 C#版

【教程】模拟登陆网站 之 Python版(内含两种版本的完整的可运行的代码)

【教程】模拟登陆网站 之 C#版(内含两种版本的完整的可运行的代码)

转载请注明:在路上 » 【教程】抓取网并提取网页中所需要的信息 之 Python版

95 queries in 0.176 seconds, using 19.38MB memory