【问题标题】:Scraping and saving tripadvisor reviews - using beautifulsoup, get_text() on python 3抓取和保存tripadvisor评论-在python 3上使用beautifulsoup、get_text()
【发布时间】:2016-03-13 23:12:42
【问题描述】:

星期天快乐!

免责声明:我对 python 很陌生(只有两周的学习时间)。

好吧,所以我使用 beautifulsoup 构建了一小段代码,用于从 tripadvisor 页面中删除评论内容并将其保存到文本文件中。

我的问题是,当我打印结果时,所有评论都会出现。但是,当我尝试将其保存到本地文本文件时,只会保存第一个评论。

这是我到目前为止的一段代码:

#prompt for URL of the page to scrap
print "                                Paste url here"
importurl = raw_input()
print "                                Import of:"
print "                                %s " %importurl
#convert the page into a soup
r = requests.get(importurl)
soup = BeautifulSoup(r.content, "lxml")
#look for the partial entry of the review
resultsoup = soup.find_all("p", {"class" : "partial_entry"})
#save the reviews to a test text file locally
for review in resultsoup:
    review_list = review.get_text()
    print review_list
    with open('testreview.txt', 'w') as fid:
        fid.write(unidecode(review_list))

【问题讨论】:

  • 什么是new_entry
  • 很好发现,损坏的代码!它应该是 review_list!

标签: python beautifulsoup


【解决方案1】:

您在循环的每次迭代中重写文件。将上下文管理器移动到循环之前:

with open('testreview.txt', 'w') as fid: 
    for review in resultsoup:
        review_list = review.get_text()
        fid.write(unidecode(review_list))

【讨论】:

  • 太棒了,谢谢你解释清楚!简单而精确。真的很感激!
猜你喜欢
  • 1970-01-01
  • 2019-09-06
  • 2018-10-29
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
  • 1970-01-01
相关资源
最近更新 更多