获取特定 div 的 span 类内的文本

2023-12-27

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


首先,如果您使用的是 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 https://t-mobile.ugc.bazaarvoice.com/9060redes2-en_us/E4F08F7E-8C29-4420-BE87-9226A6C0509D/reviews.djs?format=embeddedhtml

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取特定 div 的 span 类内的文本 的相关文章

随机推荐