23213ew 发表于 2016-3-8 08:25:35

Python爬虫爬数据写入到文件


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#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=
    name=td.text.strip()
    hex=td.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.get('style')
    tds=trs.find_all('td')
    name=tds.text
    hex=tds.text
    print('颜色:'+name+'颜色值:'+hex+'背景色样式'+style)
'''


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

页: [1]
查看完整版本: Python爬虫爬数据写入到文件