python抓取网页例子

最近在学习python,刚刚完成了一个网页抓取的例子,通过python抓取全世界所有的学校以及学院的数据,并存为xml文件。数据源是人人网。

因为刚学习python,写的代码还不够Pythonic。

核心代码如下:



#!/usr/bin/python

import urllib.request
from html.parser import HTMLParser
import json
import time
import xml.dom.minidom
import os class Dept():
id = 0
name = '' class University(Dept):
depts = [] class City(Dept):
universities = [] class Country(Dept):
cities = [] class MyHtmlParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.links = []
self.depts = []
def handle_starttag(self, tag, attrs):
if tag == 'option':
for att in attrs:
for a in att:
if a != 'value' and a != '':
self.depts.append(a)
def readDept(code):
depts = []
html = ''
for word in urllib.request.urlopen('http://www.renren.com/GetDep.do?id=' + str(code)).readlines():
real = word.strip().decode('gbk')
html = html + real
hp = MyHtmlParser()
hp.feed(html)
for inst in hp.depts:
dept = Dept()
dept.name = inst
depts.append(dept)
return depts def writeXml(city):
impl = xml.dom.minidom.getDOMImplementation()
dom = impl.createDocument(None, 'city', None)
root = dom.documentElement
filename = city.name + '.xml'
if os.path.isfile(filename):
os.remove(filename)
nameE = dom.createElement('name')
nameT = dom.createTextNode(city.name)
idE = dom.createElement('id')
idT = dom.createTextNode(str(city.id))
nameE.appendChild(nameT)
idE.appendChild(idT)
root.appendChild(nameE)
root.appendChild(idE)
univs = dom.createElement('universities')
root.appendChild(univs)
for uni in city.universities:
# print('write xml' + city.name + '\t' + uni.name)
universityE = dom.createElement('university')
univs.appendChild(universityE)
uniE = dom.createElement('name')
uniT = dom.createTextNode(uni.name)
uidE = dom.createElement('id')
uidT = dom.createTextNode(str(uni.id))
uniE.appendChild(uniT)
uidE.appendChild(uidT)
universityE.appendChild(uniE)
universityE.appendChild(uidE)
deptsE = dom.createElement('departments')
universityE.appendChild(deptsE)
for dep in uni.depts:
deptE = dom.createElement('department')
deptsE.appendChild(deptE)
deptNameE = dom.createElement('name')
deptIdE = dom.createElement('id')
deptT = dom.createTextNode(dep.name)
deptIdT = dom.createTextNode(str(dep.id))
deptNameE.appendChild(deptT)
deptIdE.appendChild(deptIdT)
deptE.appendChild(deptNameE) f= open(filename, 'w', encoding='utf-8')
dom.writexml(f, addindent=' ', newl='\n',encoding='utf-8')
print('write xml :' + city.name + '.xml')
f.close() def mkdir(path): path=path.strip()
path=path.rstrip("/")
isExists=os.path.exists(path)
if not isExists:
os.makedirs(path) def readData(content):
counties = []
jdata = json.loads(content)
for i in range(0,100):
try:
country = Country()
country.name = jdata[i]['name']
country.id = jdata[i]['id']
provs = jdata[i]['provs']
for prov in provs:
city = City()
city.name = prov['name']
city.id = prov['id']
country.cities.append(city)
city.universities = []
for dic in prov['univs']:
university = University()
university.id = dic['id']
university.name = dic['name']
# print('get data: \t' + university.name)
university.depts = readDept(university.id)
city.universities.append(university)
print('city = ' + city.name + '\tuniversity = ' + university.name)
writeXml(city)
counties.append(country)
except IndexError:
break;
return counties print('开始时间:' + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
f = open('data','r' )
content = f.read()
f.close()
counties = readData(content)
print('结束时间:' + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))

其中data是从如下网站拿到的

http://s.xnimg.cn/allunivlist.js

python抓取网页例子的更多相关文章

  1. Python 抓取网页并提取信息(程序详解)

    最近因项目需要用到python处理网页,因此学习相关知识.下面程序使用python抓取网页并提取信息,具体内容如下: #---------------------------------------- ...

  2. Python抓取网页中的图片到本地

    今天在网上找了个从网页中通过图片URL,抓取图片并保存到本地的例子: #!/usr/bin/env python # -*- coding:utf- -*- # Author: xixihuang # ...

  3. python抓取网页引用的模块和类

    在Python3.x中,我们可以使用urlib这个组件抓取网页,urllib是一个URL处理包,这个包中集合了一些处理URL的模块,如下:1.urllib.request模块用来打开和读取URLs:2 ...

  4. python抓取网页中图片并保存到本地

    #-*-coding:utf-8-*- import os import uuid import urllib2 import cookielib '''获取文件后缀名''' def get_file ...

  5. python抓取网页过程

    准备过程 1.抓取网页的过程 准备好http请求(http request)->提交对应的请求->获得返回的响应(http response)->获得网页源码 2.GET还是POST ...

  6. python 抓取网页一部分

    import re import requests from bs4 import BeautifulSoup response = requests.get("https://jecvay ...

  7. 浅谈如何使用python抓取网页中的动态数据

    我们经常会发现网页中的许多数据并不是写死在HTML中的,而是通过js动态载入的.所以也就引出了什么是动态数据的概念, 动态数据在这里指的是网页中由Javascript动态生成的页面内容,是在页面加载到 ...

  8. 网络爬虫-使用Python抓取网页数据

    搬自大神boyXiong的干货! 闲来无事,看看了Python,发现这东西挺爽的,废话少说,就是干 准备搭建环境 因为是MAC电脑,所以自动安装了Python 2.7的版本 添加一个 库 Beauti ...

  9. python抓取网页图片

    本人比较喜欢海贼王漫画,所以特意选择了网站http://www.mmonly.cc/ktmh/hzw/list_34_2.html来抓取海贼王的图片. 因为是刚刚学习python,代码写的不好,不要喷 ...

随机推荐

  1. POJ 1944 - Fiber Communications

    原题地址:http://poj.org/problem?id=1944 题目大意:有n个点排成一圈,可以连接任意两个相邻的点,给出 p 对点,要求这 p 对点必须直接或间接相连,求最少的连接边数 数据 ...

  2. VC2005从开发MFC ActiveX ocx控件到发布到.net网站的全部过程

      开篇语:最近在弄ocx控件发布到asp.net网站上使用,就是用户在使用过程中,自动下载安装ocx控件.(此文章也是总结了网上好多人写的文章,我只是汇总一下,加上部分自己的东西,在这里感谢所有在网 ...

  3. BZOJ 4004 装备购买

    md有毒卡什么精度!!!! 最大线性无关组(线性基)可作为模板. #include<iostream> #include<cstdio> #include<cstring ...

  4. 旧书重温:0day2【1】 简单的缓冲区溢出案例

    0x01 准备: VMwarePlayer (我是在360软件管家那搜到的下载的) xp sp2 http://user.qzone.qq.com/252738331/blog/1357138598 ...

  5. XE7 - 升级及初步使用

    春节没抢到回家的票,正好有时间把Delphi2010升级到了XE7. 用了快一个月了,今天算是补记. 安装包用了lsuper大侠整理的lsuper.XE7.Update1.v10.1.拜谢!比较顺利的 ...

  6. final修饰符,finally,finalize区别

    1.final 如果一个类被声明为final,意味着它不能再派生出新的子类,不能作为父类被继承.因此,一个类不能即被声明为abstract,又被声明为final.将变量或方法声明为final,可以保证 ...

  7. SmartWeatherAPI_Lite_WebAPI C# 获取key加密

    中国气象局面向网络媒体.手机厂商.第三方气象服务机构等用户,通过 web 方式提供数据气象服务的官方载体. 在一周前已经申请到appid,但是苦于没有C#版的key 的算法,一直验证不通过,经过几天查 ...

  8. Shell 的source命令

    source命令用法: source FileName 作用:在当前bash环境下读取并执行FileName中的命令. 注:该命令通常用命令“.”来替代. 如:source .bash_rc 与 . ...

  9. mysql (master/slave)复制原理及配置

    1 复制概述 Mysql内建的复制功能是构建大型,高性能应用程序的基础.将Mysql的数据分布到多个系统上去,这种分布的机制,是通过将Mysql的某一台主机的数据复制到其它主机(slaves)上,并重 ...

  10. python 传入参数返回的时候好像有些时候会出现莫名其妙的循环

    def handle_field(name, s_len, s): #some code #return s would error but return not.... #return s for ...