如何保存从网站上刮下的文本文件中的数据?

时间:2014-12-04 20:58:10

标签: python

import urllib.request
import re    
text_file = open("scrape.txt","w")
html = urllib.request.urlopen("http://en.wikipedia.org/wiki/Web_scraping")
text = html.read()
pattern = re.compile(b'<span dir="auto">(.+?)</span>')
key = re.findall(pattern, text)
text_file.write(key)

它返回此错误:

  

追踪(最近一次通话):      在       text_file.write(钥匙)   TypeError:必须是str,而不是list

1 个答案:

答案 0 :(得分:3)

这一行:

key = re.findall(pattern, text)

返回一个列表,在这一行:

text_file.write(key)

你想保存一个字符串。

所以你(可能)想要的是:

for found in key:
  text_file.write(found)
相关问题