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. bootstrapValidator对于隐藏域验证和程序赋值即时验证的问题

    问题1: 如下代码: <input type="hidden" name="productId"/> $("#addForm") ...

  2. Tyvj 1085 派对

    这道题和HDU 1016的素数环那道题很相似. 虽然1A了,但写代码的过程中还是丢三落四的. 贴完代码闪人,嘿嘿 //#define LOCAL #include <iostream> # ...

  3. org.hibernate.AnnotationException: No identifier specified for entity: cn.itcast.domain.Counter

    因为我的hibernate映射表没有主键所以报这个错. 解决方案是: 1.创建一个主键 2.hibernate处理无主键的表的映射问题,其实很简单,就是把一条记录看成一个主键,即组合主键<com ...

  4. codevs 4919 线段树练习4

    线段树水题.我是ziliuziliu,我是最强的#include<iostream> #include<cstdio> #include<cstring> #inc ...

  5. xcode安装app

    安装 xcode 安装 xcode command line tool 检查是否安装 在终端中运行: xcrun simctl list 如果出现所有的 Device Types,则可以进行第3步 如 ...

  6. pg 匹配中文字符

    用到了正则表达式: 字段 ~'[\u4E00-\u9FA5]+$'; 注意:此表达式可能还不能取到最全的值.

  7. 查看造成等待事件的具体SQL语句

    先查看存在的等待事件:col event for a40col WAIT_CLASS format a20select sid,WAIT_CLASS,event,p1,p2,p3,WAIT_TIME, ...

  8. Java异常体系结构

    1)系统错误(system error)是由Java虚拟机抛出的,用Error类表示.Error类描述的是内部系统错误.这样的错误很少发生.如果发生,除了通知用户以及尽量稳妥地终止程序外,几乎什么都不 ...

  9. 【转】如何调整CHM文件中的字体!非常有爱!

    原文网址:http://www.cnblogs.com/lijh_ray/archive/2011/01/25/1944668.html 如果html中字体大小是用像素px来定义,那么在IE中无法调整 ...

  10. 在Android中使用并发来提高速度和性能

    Android框架提供了很实用的异步处理类.然而它们中的大多数在一个单一的后台线程中排队.当你需要多个线程时你是怎么做的? 众所周知,UI更新发生在UI线程(也称为主线程).在主线程中的任何操作都会阻 ...