【问题标题】:Basic Python BeautifulSoup web-scraping Tripadvisor reviews and data cleaning基本 Python BeautifulSoup 网络抓取 Tripadvisor 评论和数据清理
【发布时间】:2018-10-29 12:46:09
【问题描述】:

我是编程和 StackOverflow 的完全初学者,我只需要从 TripAdvisor 页面进行一些基本的网络抓取并从中清除一些有用的信息。很好地展示它等等。我试图隔离咖啡馆的标题、评级数量和评级本身。我想我可能需要将其转换为文本并使用正则表达式或其他东西?我真的不知道。我的意思的一个例子是:

输出:

Coffee Cafe,5 分中有 4 分,201 条评论。

类似的东西。我将把我的代码放在下面,我能得到的任何帮助都会令人惊叹,我将无限感激。干杯。

from bs4 import BeautifulSoup

def get_HTML(url):
    response = urllib.request.urlopen(url)
    html = response.read()
    return html


Tripadvisor_reviews_HTML=get_HTML(
'https://www.tripadvisor.com.au/Restaurants- 
 g255068-c8-Brisbane_Brisbane_Region_Queensland.html')


def get_review_count(HTML):
    soup = BeautifulSoup(Tripadvisor_reviews_HTML, "lxml")
    for element in soup(attrs={'class' : 'reviewCount'}):
        print(element)

get_review_count(Tripadvisor_reviews_HTML)

def get_review_score(HTML):
    soup = BeautifulSoup(Tripadvisor_reviews_HTML, "lxml")
    for four_point_five_score in soup(attrs={'alt' : '4.5 of 5 bubbles'}):
        print(four_point_five_score)


get_review_score(Tripadvisor_reviews_HTML)

def get_cafe_name(HTML):
    soup = BeautifulSoup(Tripadvisor_reviews_HTML, "lxml")
    for name in soup(attrs={'class' : "property_title"}):
        print(name)



get_cafe_name(Tripadvisor_reviews_HTML)

【问题讨论】:

  • 代码有什么问题?
  • 据我所知,没有。我只是不知道如何从大块的 HTML 中清除/隔离标题、评论分数和评论计数。我该怎么办?以某种方式将其转换为文本文件并使用正则表达式?我只是卡住了,我到处寻找如何继续的例子,但到目前为止还没有运气......
  • 那么,代码现在做什么?它打印什么?这不是你想要的吗?

标签: python python-3.x web-scraping beautifulsoup data-cleaning


【解决方案1】:

您忘记在每个打印语句中使用.text。但是,请尝试以下方法从该站点获取所有三个字段。

from bs4 import BeautifulSoup
import urllib.request

URL = "https://www.tripadvisor.com.au/Restaurants-g255068-c8-Brisbane_Brisbane_Region_Queensland.html"

def get_info(link):
    response = urllib.request.urlopen(link)
    soup = BeautifulSoup(response.read(),"lxml")
    for items in soup.find_all(class_="shortSellDetails"):
        name = items.find(class_="property_title").get_text(strip=True)
        bubble = items.find(class_="ui_bubble_rating").get("alt")
        review = items.find(class_="reviewCount").get_text(strip=True)
        print(name,bubble,review)

if __name__ == '__main__':
    get_info(URL)

你可能会得到如下结果:

Double Shot New Farm 4.5 of 5 bubbles 218 reviews
Goodness Gracious Cafe 4.5 of 5 bubbles 150 reviews
New Farm Deli & Cafe 4.5 of 5 bubbles 273 reviews
Coffee Anthology 4.5 of 5 bubbles 116 reviews

【讨论】:

  • 运行完上述脚本@noob123,别忘了在这里留下反馈。
  • 哇,谢谢!效果很好!关于如何获取此输出并显示在某种表格中的任何想法?
  • 您知道打印items 中所有可能的可访问字段的方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-31
  • 2019-09-06
  • 2014-10-28
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
相关资源
最近更新 更多