【问题标题】:How do I write web-scraped text into csv using python?如何使用 python 将网络抓取的文本写入 csv?
【发布时间】:2016-10-14 08:12:20
【问题描述】:

我一直在开发一个实践网络抓取工具,它可以获取书面评论并将其写入 csv 文件,每条评论都有自己的行。我遇到了麻烦:

  1. 我似乎无法删除 html 并仅获取文本(即书面评论,仅此而已)
  2. 甚至在我的评论文本之间和内部都有很多奇怪的空格(即行之间的一排空格等)

感谢您的帮助!

代码如下:

#! 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


【解决方案1】:

您可以使用row.get_text(strip=True) 从您选择的p.partial_entry 中获取文本。请尝试以下操作:

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')

with open('GardensbytheBay.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=' ')

    # Looping until the 5th page of reviews
    for pagecounter in range(6):

        # 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('p.partial_entry')

        if reviewElems:
            for row in reviewElems:
                review_text = row.get_text(strip=True).encode('utf8', 'ignore').decode('latin-1')
                writer.writerow([review_text])
            print('Writing page', pagecounter + 1)
        else:
            print('Could not find clue.')

        # 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')

print('Download complete')

【讨论】:

  • 谢谢!这太棒了。 :)
猜你喜欢
  • 2022-09-27
  • 2019-03-12
  • 2019-11-12
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
  • 2019-03-06
  • 1970-01-01
相关资源
最近更新 更多