2014-12-04 34 views
-2
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) 

和返回該錯誤:如何將數據保存在網站中的文本文件中?

Traceback (most recent call last): in text_file.write(key) TypeError: must be str, not list

+0

它不工作。現在發生的錯誤是:Traceback(最近調用最後一次):text_file.write(找到)TypeError:必須是str,而不是bytes.How應該解決這個問題嗎? – Anaya 2014-12-05 13:45:53

回答

3

這條線:

key = re.findall(pattern, text) 

返回一個列表,在這條線,其中:

text_file.write(key) 

您要保存串。

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

for found in key: 
    text_file.write(found) 
相關問題