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. Winform——计算器

    namespace 计算器2._0 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } pr ...

  2. 51nod1158 全是1的最大子矩阵

    跟最大子矩阵差不多O(n3)扫一下.有更优写法?挖坑! #include<cstdio> #include<cstring> #include<cctype> #i ...

  3. 未能加载文件或程序集“XXXXXX”或它的某一个依赖项。试图加载格式不正确的程序。

    在本机WIN7机器上的WebService部署到Win2008R2上发现错误 “/”应用程序中的服务器错误. 未能加载文件或程序集“XXXXXX”或它的某一个依赖项.试图加载格式不正确的程序. 说明: ...

  4. NHibernate实例化类部分属性

    NHibernate 为习惯SQL的开发者提供了接口,将查询的结果转变为持久化对象.虽然该方法不是很提倡. GetCurrentSession().CreateSQLQuery(sql) 参数sql就 ...

  5. notepad 行替换使用指南

    notepad++是开源的文本处理软件,性能堪比ultraedit,不过在转用notepad++之后一直为他的行替换功能纠结,UE当中只需要用 [^p] 就可以表示一行,但是在notepad++当中, ...

  6. 在ACCESS中创建数据库和查询(ACCESS 2000)

    备份还原数据库 备份.还原 —— 复制\粘贴 压缩修复数据库命令 —— 复制该文件并重新组织,并重新组织文件在磁盘上的储存方式.压缩同时优化了Access数据库的性能.(工具——实用数据库工具或者工具 ...

  7. [Everyday Mathematics]20150222

    设 $$\bex a_0=1,\quad a_1=\frac{1}{2},\quad a_{n+1}=\frac{na_n^2}{1+(n+1)a_n}\ (n\geq 1). \eex$$ 试证: ...

  8. eclipse插件explorer安装使用

    我们知道myeclipse有个open in explorer的按钮.可以方便我们打开任意IDC下的文件或则插件目录 但是eclipse下确没有.因此需要下载下载个eclipse explorer插件 ...

  9. YII Framework学习教程-YII的异常处理

    异常无处不在,作为程序员,活着就是为了创造这些异常,然后修复这些异常而存在的.YII框架封装了PHP的异常,让异常处理起来更简单. 使用 YII处理错误和异常的配置方法: 你可以在入口文件中定义YII ...

  10. linux下磁盘的挂载与卸载

    Linux下每个文件系统都有独立的inode,block,super block等信息,这个文件系统要挂载到目录树才可以使用,将文件系统与目录树结合的操作称为挂载,反之则为卸载. 也就是说,挂载点一定 ...