首页 > 编程语言 > 详细

Python爬虫爬数据写入到文件

时间:2016-03-08 00:36:13      阅读:209      评论:0      收藏:0      [点我收藏+]
#coding=utf-8
import requests
from bs4 import BeautifulSoup
import sys
reload(sys)  
sys.setdefaultencoding(‘utf8‘) 
r=requests.get(‘http://html-color-codes.info/color-names/‘)
html=r.text
#print html
soup=BeautifulSoup(html,‘html.parser‘)
trs=soup.find_all(‘tr‘)
f=open(‘color.txt‘,‘a‘)
index=1
for tr in trs:
	style=tr.get(‘style‘)
	tds=tr.find_all(‘td‘)
	td=[x for x in tds]
	name=td[1].text.strip()
	hex=td[2].text.strip()
	string=str(index)+‘,‘+name+‘,‘+hex+‘,‘+style
	f.write(string)
	f.write(‘\r\n‘)
	#print(‘序号:‘+str(index)+‘颜色:‘+name+‘颜色值:‘+hex+‘背景色样式‘+style)
	index=index+1
f.close()
‘‘‘
for index in range(len(trs)):
	style=trs[index].get(‘style‘)
	tds=trs[index].find_all(‘td‘)
	name=tds[1].text
	hex=tds[2].text
	print(‘颜色:‘+name+‘颜色值:‘+hex+‘背景色样式‘+style)
‘‘‘

直接上代码。本来这次是想抓取数据直接通过mysql相关的包写入到数据库来着,结果在网上找教程的时候发现MySQL那玩意好难安装。。。。。所以就直接放弃了。间接的把数据先写进txt文本,再慢慢导进数据库吧。。。。

Python爬虫爬数据写入到文件

原文:http://fulin0532.blog.51cto.com/6233825/1748605

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!