在特定div的span类中获取文本

问题描述 投票:-1回答:3

我正在抓住T-Mobile网站上的三星Galaxy S9评论。我能够为HTML代码创建一个Beautiful Soup对象,但我无法获取span类中存在的评论文本,还需要遍历评论页面以收集所有评论。

我尝试了2个代码,但其中一个返回错误,另一个返回空列表。我也找不到汤对象中我需要的特定span类。

from urllib.request import Request, urlopen
from bs4 import BeautifulSoup

tmo_ratings_s9 = []

req = Request('https://www.t-mobile.com/cell-phone/samsung-galaxy-s9', headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()
tmo_soup_s9 = BeautifulSoup(webpage, 'html.parser')
tmo_soup_s9.prettify()
for review in tmo_soup_s9.find_all(class_="BVRRReviewText"):
    text = review.span.get_text(strip=True)
    tmo_soup_s9.append(text)

print(tmo_ratings_s9)


############################################################################

from urllib.request import urlopen
html = urlopen("https://www.t-mobile.com/cell-phone/samsung-galaxy-s9")

soup=BeautifulSoup(html)

ratings = soup.find_all('div', class_='BVRRReviewTextParagraph BVRRReviewTextFirstParagraph BVRRReviewTextLastParagraph')     
textofrep = ratings.get_text().strip()
tmo_ratings_s9.append(textofrep)

我希望从网页上的所有8个页面获取评论文本,并将它们存储在HTML文件中。

python html web-scraping
3个回答
1
投票

由于通过脚本加载动态内容,您无法获取数据。你可以尝试硒和scrapy。

import scrapy
from selenium import webdriver
from scrapy.http import HtmlResponse

class ProductSpider(scrapy.Spider):
    name = "product_spider"
    allowed_domains = ['t-mobile.com']
    start_urls = ['https://www.t-mobile.com/cell-phone/samsung-galaxy-s9']

    def __init__(self):
        self.driver = webdriver.Firefox()

    def parse(self, response):
        self.driver.get(response.url)
        body = str.encode(self.driver.page_source)
        self.parse_response(HtmlResponse(self.driver.current_url, body=body, encoding='utf-8'))

    def parse_response(self, response):
        tmo_ratings_s9 = []
        for review in response.css('#reviews div.BVRRContentReview'):
            text = review.css('.BVRRReviewText::text').get().strip()
            tmo_ratings_s9.append(text)

        print(tmo_ratings_s9)

    def spider_closed(self, spider, reason):
        self.driver.close()

2
投票

首先,如果您使用谷歌浏览器或Mozilla Firefox,请从页面按ctrl + u,然后您将转到页面源。通过搜索某些关键字,检查源中的任何位置是否存在评论内容。如果存在,则写入该数据的xpath,如果不存在,请检查网络部分以查找在页面加载时发送的任何json请求,如果不存在,则必须使用selenium。

在您的情况下发送请求到此页面https://t-mobile.ugc.bazaarvoice.com/9060redes2-en_us/E4F08F7E-8C29-4420-BE87-9226A6C0509D/reviews.djs?format=embeddedhtml

这是在加载整个页面时发送的json请求。


© www.soinside.com 2019 - 2024. All rights reserved.