python批量获取html内body内容的实例

现在有一批完整的关于介绍城市美食、景点等的html页面,需要将里面body的内容提取出来

方法:利用python插件beautifulSoup获取htmlbody标签的内容,并批量处理。

# -*- coding:utf8 -*-

from bs4 import BeautifulSoup
import os
import os.path
import sys
reload(sys)
sys.setdefaultencoding('utf8') 

def printPath(level,path):
	global allFileNum
	#所有文件夹,第一个字段是此目录的级别
	dirList = []

	#所有文件
	fileList = []

	#返回一个列表,其中包含在目录条目的名称
	files = os.listdir(path)

	#先添加目录级别
	dirList.append(str(level))

	for f in files:
		if(os.path.isdir(path+'/'+f)):
			#排除隐藏文件夹,因为隐藏文件夹过多
			if(f[0] == '.'):
				pass
			else:
				#添加隐藏文件夹
				dirList.append(f)
		if(os.path.isfile(path+'/'+f)):
			#添加文件
			fileList.append(f)
	return (dirList,fileList)

#将文件html文件抓取并写入指定txt文件
def getAndInsert(rootdir,savepath,path):
	global file_num
	f_list = os.listdir(rootdir+'/'+path)
	for i in f_list:
		temp = os.path.splitext(i)[0]
		for num in range(1,11):
			if(i==str(num)+'.html'):
				#print rootdir+'/'+path+'/'+i
				objFile = open(rootdir+'/'+path+'/'+i)
				soup = BeautifulSoup(objFile)
				arr = []
				for child in soup.body:
					arr.append(child)
				if os.path.exists(savepath+'/'+path):
					pass
				else:
					os.makedirs(savepath+'/'+path)
				f = open(savepath+'/'+path+'/'+temp+'.txt','w')
				for k,v in enumerate(arr):
					if k!=1:
						f.write(str(v))
				f.close()
				print path+'/'+i+' is running'
	file_num = file_num + 1

rootdir = '../zips2'
dirList,fileList = printPath(1,rootdir)

savepath = "../testC"
file_num = 0

for fn in dirList:
	if(fn == '1'):
		pass
	else:
		getAndInsert(rootdir,savepath,fn)
		print fn+' is ending'
print '一共完成'+str(file_num)+'个城市的提取'

以上这篇python批量获取html内body内容的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Python 抓取动态网页内容方案详解

    用Python实现常规的静态网页抓取时,往往是用urllib2来获取整个HTML页面,然后从HTML文件中逐字查找对应的关键字.如下所示: 复制代码 代码如下: import urllib2 url="http://mm.taobao.com/json/request_top_list.htm?type=0&page=1" up=urllib2.urlopen(url)#打开目标页面,存入变量up cont=up.read()#从up中读入该HTML文件 key1='<a

  • python3爬虫获取html内容及各属性值的方法

    今天用到BeautifulSoup解析爬下来的网页数据 首先导入包from bs4 import BeautifulSoup 然后可以利用urllib请求数据 记得要导包 import urllib.request 然后调用urlopen,读取数据 f=urllib.request.urlopen('http://jingyan.baidu.com/article/455a9950bc94b8a166277898.html') response=f.read() 这里我们就不请求数据了,直接用本

  • 用python3教你任意Html主内容提取功能

    本文将和大家分享一些从互联网上爬取语料的经验. 0x1 工具准备 工欲善其事必先利其器,爬取语料的根基便是基于python. 我们基于python3进行开发,主要使用以下几个模块:requests.lxml.json. 简单介绍一个各模块的功能 01|requests requests是一个Python第三方库,处理URL资源特别方便.它的官方文档上写着大大口号:HTTP for Humans(为人类使用HTTP而生).相比python自带的urllib使用体验,笔者认为requests的使用体

  • python批量获取html内body内容的实例

    现在有一批完整的关于介绍城市美食.景点等的html页面,需要将里面body的内容提取出来 方法:利用python插件beautifulSoup获取htmlbody标签的内容,并批量处理. # -*- coding:utf8 -*- from bs4 import BeautifulSoup import os import os.path import sys reload(sys) sys.setdefaultencoding('utf8') def printPath(level,path)

  • Python批量获取并保存手机号归属地和运营商的示例

    从Excel读取一组手机号码,批量查询该手机号码的运营商和归属地,并将其追加到该记录的末尾. import requests import json import xlrd from xlutils.copy import copy host = 'https://cx.shouji.360.cn/phonearea.php' # excel文件路径 file_path = "F:\\temp.xlsx" # 新文件路径 new_file_path = "F:\\temp(含

  • Python批量获取基金数据的方法步骤

    20年初准备投资基金,想爬取基金的业绩数据. 20年基金迎来了爆发式增长,现把代码开源以供参考. 本代码只能实现初步汇总,输出csv文件来保存基金的单位&累计净值,后期仍需要结合统计方法来筛选优质基金. 参考了网上的部分代码,实在不记得出处了,侵删. import requests import time import execjs start = time.perf_counter() # 获取所有基金编号 def getAllCode(): url = 'http://fund.eastmo

  • Python过滤txt文件内重复内容的方法

    Python过滤txt文件内重复内容,并将过滤后的内容保存到新的txt中 示例如下 原文件 处理之后的文件 直接上代码 # -*-coding:utf-8 -*- f = open("1.txt", "rb") n = f.read() f.close() m = n.split("\r\n") print "m=",m print m[1] m1 = [] for i in xrange(len(m)): if not m[

  • 在python中获取div的文本内容并和想定结果进行对比详解

    div的内容为: <div style="background-color: rgb(255, 238, 221);" id="status" class="errors">您输入的用户名或密码有误.</div> # coding:utf-8 from selenium import webdriver browser = webdriver.Firefox() url = 'file:///C:/Users/li/Des

  • Python 批量合并多个txt文件的实例讲解

    实例如下所示: # -*- coding:utf-8 -*- #os模块中包含很多操作文件和目录的函数 import os #获取目标文件夹的路径 meragefiledir = os.getcwd()+'\\MerageFiles' #获取当前文件夹中的文件名称列表 filenames=os.listdir(meragefiledir) #打开当前目录下的result.txt文件,如果没有则创建 file=open('result.txt','w') #向文件中写入字符 #先遍历文件名 for

  • 使用python serial 获取所有的串口名称的实例

    如下所示: #!/usr/bin/env python # -*- coding: utf-8 -* import serial import serial.tools.list_ports port_list = list(serial.tools.list_ports.comports()) if len(port_list) <= 0: print "The Serial port can't find!" else: port_list_0 =list(port_list

  • Python+Pandas 获取数据库并加入DataFrame的实例

    实例如下所示: import pandas as pd import sys import imp imp.reload(sys) from sqlalchemy import create_engine import cx_Oracle db=cx_Oracle.connect('userid','password','10.10.1.10:1521/dbinstance') print db.version cr=db.cursor() sql='select * from sys_user

  • Python+selenium 获取一组元素属性值的实例

    获取一组href元素属性的值 lst = driver.find_elements_by_class_name("ib-it-text") for lst in lst: lst = lst.get_attribute("href") print(lst.get_attribute("href")) 以上这篇Python+selenium 获取一组元素属性值的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • python批量替换文件名中的共同字符实例

    今天看新概念视频的时候播放器PotPlayer的播放列表总是不能正确排序,我看到这些视频的名字格式如下: Lesson 1-2 单词解读.mp4 我认为是数字前面的Lesson和空格干扰了播放器的排序,就考虑把这个文件夹下所有的文件名批量删除Lesson和空格,使之变成: 1-2 单词解读.mp4 这里主要使用的就是os模块下的listdir,chadir和rename三个方法 虽然最后还是排序不正确,我只能怪播放器不好了. 代码如下 # -*- coding: UTF-8 -*- import

随机推荐