我正在使用以下代码来抓取Google建议:
return
输入文件:
with open(inputfile, 'r', encoding="ISO-8859-1") as inputf:
for line in inputf:
line = line.strip("\n")
URL="http://suggestqueries.google.com/complete/search?client=firefox&q=" + line
headers = {'User-agent':'Mozilla/5.0'}
response = requests.get(URL, headers=headers)
result = json.loads(response.content.decode('utf-8'))
print(result)
with open(outputfile, 'a') as file:
for num in range(len(result)):
file.write(result[num] + '\n')
print('wrote: %s ' %(result[num]))
json输出:
online games
ofline games
free online games
mods
game
gaming
我想要的是将每个结果输出到文本文件中的新行。 例如:
['game', ['game mania', 'game of thrones', 'games', 'game of thrones season 8',
'game of thrones season 7', 'game night', 'gamemeneer', 'gamegear',
'game pc', 'gamescom']]
但出现以下错误:
game mania\n
game of thrones\n
games\n
ect
答案 0 :(得分:1)
将输出保存到列表中,然后像这样将值添加到文本文件中时遍历该列表:
mylist = ['one','two','three']
with open('newtext.txt', 'a') as file:
for num in range(len(mylist)):
file.write(mylist[num] + '\n')
print('wrote: %s ' %(mylist[num]))
newtext.txt
一个
两个
三个