从多个网站抓取文本并单独保存在文本文件中



我是python的初学者,一直在使用它作为我的硕士论文,在游戏行业中进行文本分析。我一直在尝试从几个游戏评论家网站上抓取评论。

我在代码中使用了URL列表来抓取评论并取得了成功。不幸的是,我无法将每个评论写在一个单独的文件中。当我编写文件时,我要么只收到从列表中最后一个 URL 到所有文件的评论,要么在更改缩进后收到所有文件中的所有评论。以下是我的代码。你能建议一下这里有什么问题吗?

from bs4 import BeautifulSoup
import requests
urls= ['http://www.playstationlifestyle.net/2018/05/08/ao-international-tennis-review/#/slide/1',
'http://www.playstationlifestyle.net/2018/03/27/atelier-lydie-and-suelle-review/#/slide/1',
'http://www.playstationlifestyle.net/2018/03/15/attack-on-titan-2-review-from-a-different-perspective-ps4/#/slide/1']  
for url in urls:
r=requests.get(url).text
soup= BeautifulSoup(r, 'lxml')
for i in range(len(urls)):
file=open('filename%i.txt' %i, 'w')    
for article_body in soup.find_all('p'):
body=article_body.text
file.write(body)
file.close()

我认为你只需要一个 for 循环。如果我理解正确,您只想循环访问urls并为每个文件存储一个单独的文件。

因此,我建议删除第二条for声明。但是,您需要修改for url in urls以获取可用于i的当前URL的唯一索引,并且可以为此使用enumerate

您的单个for语句将变为:

for i, url in enumerate(urls):

我自己没有测试过这个,但我认为这应该可以解决你的问题。

我完全相信你是python的初学者。在解释之前,我会发布正确的一个。

for i,url in enumerate(urls):
r = requests.get(url).text
soup = BeautifulSoup(r, 'lxml')
file = open('filename{}.txt'.format(i), 'w')
for article_body in soup.find_all('p'):
body = article_body.text
file.write(body)
file.close()

i receive only the review from the last URL in the list to all the files的原因

一个变量代表一个值,所以在for循环完成后,你会得到最后一个结果(第三个(。第一个和第二个结果的结果将被覆盖

for url in urls:
r = requests.get(url).text
soup = BeautifulSoup(r, 'lxml') 

最新更新