Python 抓取网页并提取信息(程序详解)
最近因项目需要用到python处理网页,因此学习相关知识。下面程序使用python抓取网页并提取信息,具体内容如下:
#------------------------------------------------------------------------------ import urllib2 # extensible library for opening URLs
import re # regular expression module #------------------------------------------------------------------------------
def main():
userMainUrl = "http://www.songtaste.com/user/351979/"
req = urllib2.Request(userMainUrl) # request
resp = urllib2.urlopen(req) # response
respHtml = resp.read() # read html
print "respHtml =", respHtml
#<h1 class="hluser">crifan</h1>
foundH1user = re.search(r'<h1\s+?class="h1user">(?P<h1user>.+?)</h1>', respHtml)
print "foundHluser =", foundH1user
if foundH1user:
h1user = foundH1user.group("h1user")
print "hluser=", h1user ###################################################################################
if __name__=='__main__':
main()
本程序实现目的,从http://www.songtaste.com/user/351979/网页源码中找到
<h1 class="hluser">crifan</h1> 再从上面的格式中提取“crifan”。 从网络中读取网页,需要2个步骤:向网页服务器请求和服务器响应。下面对程序核心的部分进行解析,如下:
foundH1user = re.search(r'<h1\s+?class="h1user">(?P<h1user>.+?)</h1>', respHtml) 本语句使用正则表达式进行匹配字符串“<h1 class="hluser">crifan</h1>”。将<h1>与</h1>之间的内容归为一个group,group名为h1user。
注意 “h1user”中‘1’是数字‘1’,不是字母‘l’
程序中涉及到相关知识如下:
1、re.search
re.search(pattern, string, flags=0)
Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.
class re.MatchObject
Match objects always have a boolean value of True.
Since match() and search() return None when there is no match, you can test whether there was a match with a simple if statement:
match = re.search(pattern, string)
if match:
process(match)
2、group([group1, ...])
Match objects support the following methods and attributes:
group([group1, ...])
Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an IndexError exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is None. If a group is contained in a part of the pattern that matched multiple times, the last match is returned.
3、(?P<name>...)
(?P<name>...),用于对group命名,group名为name,从而可以通过group('name'),实现对此group进行访问。如程序中
foundH1user.group("h1user")
其中foundH1user为MatchObject instance,h1user为group名
与正常的括号类似,但是按group匹配的子串可通过象征性的group名name访问。group名必须是有效的Python标识符,每个组名在正则表达式中只能定义一次。具有symbolic group name的组也是一个有编号的组,就好像这个group没有被命名一样
Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named.
4、程序中使用的正则表达式符号
常用的元字符
\s 匹配任意的空白符
. 匹配除换行符以外的任意字符
常用的限定符
+ 重复一次或更多次
? 重复零次或一次
由正则表达式的符号含义可知,程序中 "\s+?" 完全可以用 "\s+" 或 ”\s?"替代
参考资料:
1、http://www.crifan.com/crawl_website_html_and_extract_info_using_python/
2、https://docs.python.org/2/library/re.html#re.MatchObject
3、http://deerchao.net/tutorials/regex/regex.htm
Python 抓取网页并提取信息(程序详解)的更多相关文章
- 我的第一个爬虫程序:利用Python抓取网页上的信息
题外话 我第一次听说Python是在大二的时候,那个时候C语言都没有学好,于是就没有心思学其他的编程语言.现在,我的毕业设计要用到爬虫技术,在网上搜索了一下,Python语言在爬虫技术这方面获得一致好 ...
- (转)如何用python抓取网页并提取数据
最近一直在学这部分,今日发现一篇好文,虽然不详细,但是轮廓是出来了: 来自crifan:http://www.crifan.com/crawl_website_html_and_extract_inf ...
- 用python抓取智联招聘信息并存入excel
用python抓取智联招聘信息并存入excel tags:python 智联招聘导出excel 引言:前一阵子是人们俗称的金三银四,跳槽的小朋友很多,我觉得每个人都应该给自己做一下规划,根据自己的进步 ...
- python抓取网页例子
python抓取网页例子 最近在学习python,刚刚完成了一个网页抓取的例子,通过python抓取全世界所有的学校以及学院的数据,并存为xml文件.数据源是人人网. 因为刚学习python,写的代码 ...
- 使用python抓取58手机维修信息
之前在ququ的博客上看到说 python 中的BeautifulSoup 挺好玩的,今天下午果断下载下来,看了下api,挺好用的,完了2把,不错. 晚上写了一个使用python抓取58手机维修信息的 ...
- python抓取网页引用的模块和类
在Python3.x中,我们可以使用urlib这个组件抓取网页,urllib是一个URL处理包,这个包中集合了一些处理URL的模块,如下:1.urllib.request模块用来打开和读取URLs:2 ...
- Python抓取网页中的图片到本地
今天在网上找了个从网页中通过图片URL,抓取图片并保存到本地的例子: #!/usr/bin/env python # -*- coding:utf- -*- # Author: xixihuang # ...
- python抓取链家房源信息(二)
试着用scrapy将之前写的抓取链家网信息的重新写了写 然后先是用了第一页的网页作为测试,调试代码,然后发现总是抓取的时候遇见了 类似于这样的问题,并且抓取不到信息 2017-03-28 17:52: ...
- python抓取网页中图片并保存到本地
#-*-coding:utf-8-*- import os import uuid import urllib2 import cookielib '''获取文件后缀名''' def get_file ...
随机推荐
- C# winform多线程的小例子
在文本框中输入一个数字,点击开始累加按钮,程序计算从1开始累计到该数字的结果.因为该累加过程比较耗时,如果直接在UI线程中进行,那么当前窗口将出现假死.为了有更好的用户体验,程序启动一个新的线程来单独 ...
- SEO站点优化学习总结
1.网站收录查询 在搜索引擎里面输入Site:域名 即可. 尾巴——学习SEO可以看看以下几个网站: 卢松松博客[一个草根的博客]:http://lusongsong.com/ 站长之家[里面有站长统 ...
- 删除root子目录,如何恢复子目录配置文件
手贱,一不小心rm -rf 问题描述:删除/root/子目录文件(含隐藏配置文件)shell变成-bash-4.2#,如何恢复原貌 解决方法: root用户进入,自己配置相关文件:mkdir /roo ...
- android 调用电话功能
今天用到了打电话的功能,这要如何实现呢? 很简单 1.创建对应对的xml展示页面喝java文件 2.在manifest中添加权限 下面上代码吧: 这是布局的一部分 <LinearLayout a ...
- Ceph浅析”系列之四——Ceph的结构
本文将从逻辑结构的角度对Ceph进行分析. Ceph系统的层次结构 Ceph存储系统的逻辑层次结构如下图所示[1]. Ceph系统逻辑层次结构 自下向上,可以将Ceph系统分为四个层次: (1)基础存 ...
- struts2 spring3.2 hibernate4.1 框架搭建 整合
ssh是企业开发中常遇到的框架组合,现将框架的搭建过程记录下来,以便以后查看.我的搭建过程是,首先struts,然后spring,最后hibernate.struts2的最新版本为2.3.8,我下载的 ...
- 【51NOD 1478】括号序列的最长合法子段
很恶心啊,一道水题改了半天,主要是各种细节没有注意到,包括左括号剩余时有可能会出错的情况,需要从后往前扫 贡献一组测试数据: ((()))())(())(( 答案:8 1 #include<cs ...
- 强连通 HDU 1269
n点m边 求是否能从任意a->b b->a 强连通分量等于1 #include<stdio.h> #include<algorithm> #include<s ...
- 微信扫码支付 php
仔细看了一遍官方的那幅流程图,我来简化理解一下(注意:我这里针对的是扫码支付模式一,模式二没什么说的)网站后台生成二维码,当然是跟据前台传来的参数有条件的生成买家扫描二维码,扫描过程中,微信后台系统回 ...
- git log 常用命令及技巧
git log常用命令以及技巧 1.git log 如果不带任何参数,它会列出所有历史记录,最近的排在最上方,显示提交对象的哈希值,作者.提交日期.和提交说明.如果记录过多,则按Page Up.Pag ...