我需要将解析结果保存在文本文件中。
import urllib
from bs4 import BeautifulSoup
import urlparse
path = 'A html file saved on desktop'
f = open(path,"r")
if f.mode == 'r':
contents = f.read()
soup = BeautifulSoup(contents)
search = soup.findAll('div',attrs={'class':'mf_oH mf_nobr mf_pRel'})
searchtext = str(search)
soup1 = BeautifulSoup(searchtext)
urls = []
for tag in soup1.findAll('a', href = True):
raw_url = tag['href'][:-7]
url = urlparse.urlparse(raw_url)
urls.append(url)
print url.path
with open("1.txt", "w+") as outfile:
for item in urls:
outfile.write(item + "\n")
但是,我得到了这个: Traceback(最近一次调用最后一次):文件“c.py”,第 26 行,在 outfile.write(item + "\n") TypeError: can only concatenate tuple (not "str") to tuple .
如何将元组转换为字符串并将其保存在文本文件中?谢谢。