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

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


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


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 文件中。


鸿蒙传说
浏览 226回答 3
3回答

慕桂英3389331

首先,如果您使用的是 google chrome 或 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 请求。

元芳怎么了

由于通过脚本加载动态内容,您无法获取数据。您可以尝试 selenium 和scrapy。import scrapyfrom selenium import webdriverfrom scrapy.http import HtmlResponseclass 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()

HUX布斯

使用 selenium 或 webscraper.iohttps://www.webscraper.io/https://www.seleniumhq.org/docs/01_introducing_selenium.jsp
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python