【发布时间】:2016-10-14 08:12:20
【问题描述】:
我一直在开发一个实践网络抓取工具,它可以获取书面评论并将其写入 csv 文件,每条评论都有自己的行。我遇到了麻烦:
- 我似乎无法删除 html 并仅获取文本(即书面评论,仅此而已)
- 甚至在我的评论文本之间和内部都有很多奇怪的空格(即行之间的一排空格等)
感谢您的帮助!
代码如下:
#! python3
import bs4, os, requests, csv
# Get URL of the page
URL = ('https://www.tripadvisor.com/Attraction_Review-g294265-d2149128-Reviews-Gardens_by_the_Bay-Singapore.html')
# Looping until the 5th page of reviews
pagecounter = 0
while pagecounter != 5:
# Request get the first page
res = requests.get(URL)
res.raise_for_status
# Download the html of the first page
soup = bs4.BeautifulSoup(res.text, "html.parser")
reviewElems = soup.select('.partial_entry')
if reviewElems == []:
print('Could not find clue.')
else:
#for i in range(len(reviewElems)):
#print(reviewElems[i].getText())
with open('GardensbytheBay.csv', 'a', newline='') as csvfile:
for row in reviewElems:
writer = csv.writer(csvfile, delimiter=' ', quoting=csv.QUOTE_ALL)
writer.writerow(row)
print('Writing page')
# Find URL of next page and update URL
if pagecounter == 0:
nextLink = soup.select('a[data-offset]')[0]
elif pagecounter != 0:
nextLink = soup.select('a[data-offset]')[1]
URL = 'http://www.tripadvisor.com' + nextLink.get('href')
pagecounter += 1
print('Download complete')
csvfile.close()
【问题讨论】:
-
2) 浏览器在显示 HTML 时不关心空格,因此人们(创建网页)也不关心空格。它们(或其函数)添加空格以使其在开发过程中更具可读性 - 浏览器在显示 HTML 时会跳过这些空格。
标签: python csv web-scraping beautifulsoup