Python爬虫爬数据写入到文件

发布时间:2019-08-31 09:41:21编辑:auto阅读(1524)

    #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文本,再慢慢导进数据库吧。。。。

关键字