Python 如何将数据保存在从网站上刮取的文本文件中? 导入urllib.request 进口稀土 text_file=open(“scrape.txt”、“w”) html=urllib.request.urlopen(“http://en.wikipedia.org/wiki/Web_scraping") text=html.read() 模式=重新编译(b'(.+?)') key=re.findall(模式、文本) text_file.write(键)

Python 如何将数据保存在从网站上刮取的文本文件中? 导入urllib.request 进口稀土 text_file=open(“scrape.txt”、“w”) html=urllib.request.urlopen(“http://en.wikipedia.org/wiki/Web_scraping") text=html.read() 模式=重新编译(b'(.+?)') key=re.findall(模式、文本) text_file.write(键),python,Python,并返回此错误: 回溯(最近一次呼叫最后一次): 在里面 text_file.write(键) TypeError:必须是str,而不是list 这一行: 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

并返回此错误:

回溯(最近一次呼叫最后一次): 在里面 text_file.write(键) TypeError:必须是str,而不是list

这一行:

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)
正在返回列表,其中此行:

key = re.findall(pattern, text)
您想保存一个字符串

因此,您(可能)想要的是:


它不起作用。现在出现的错误是:Traceback(最近一次调用last):text_file.write(found)TypeError:必须是str,而不是bytes。我应该如何解决这个问题??
text_file.write(key)
for found in key:
  text_file.write(found)