【问题标题】:beautifulsoup return empty value美丽的汤返回空值
【发布时间】:2018-04-18 22:19:40
【问题描述】:

我正在使用 Jupyter Python 2.7 我试图从这个网站检索数据,一切顺利,使用 beautifulsoup 和 lxml 解析器来抓取描述或价格。

网站 = 'https://www.bedbathandbeyond.com/store/product/dyson-v7-motorhead-cord-free-stick-vacuum-in-fuchsia-steel/1061083288?brandId=162'

但是,当我试图抓取评论者的 cmets 或位置时,我无法检索任何内容,只有一个空列表 []

我也尝试过 PyQt4 先渲染它,但它仍然不起作用。我现在应该如何解决?

我的代码附在下面

import PyQt4
from PyQt4.QtGui import *  
from PyQt4.QtCore import *  
from PyQt4.QtWebKit import * 
import sys
from lxml import html
from bs4 import BeautifulSoup
import os
import requests

site = 'https://www.bedbathandbeyond.com/store/product/dyson-v7-motorhead-cord-free-stick-vacuum-in-fuchsia-steel/1061083288?brandId=162'

class Render(QWebPage):     
    def __init__(self, url):
        self.app = QApplication(sys.argv)  
        QWebPage.__init__(self)  
        self.loadFinished.connect(self._loadFinished)  
        self.mainFrame().load(QUrl(url))  
        self.app.exec_()   
    def _loadFinished(self, result):  
        self.frame = self.mainFrame()  
        self.app.quit()
r = Render(site)  
result = r.frame.toHtml()
formatted_result = str(result.toAscii())
tree = html.fromstring(formatted_result)
soup = BeautifulSoup(formatted_result,'lxml')
soup.find_all('span', class_ = 'BVRRValue BVRRUserLocation')#return value is []

非常感谢!

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup pyqt4


    【解决方案1】:

    我快速检查了引用的 URL,只有在您单击“评分和评论”选项卡后,评论才会通过异步调用加载。因此,如果您只是在没有任何额外导航的情况下加载页面,评论将不会出现在 DOM 中(因此不会出现在您使用 BeautifulSoup 解析的 HTML 中)。

    因此,一种解决方案是在获取 HTML 并将其传递给 BeautifulSoup 之前简单地触发对“评分和评论”的点击。

    或者,您也可以进行相同的异步调用来自己获取评论。通过对该页面执行 GET 请求来检索评论的第一页:https://bedbathandbeyond.ugc.bazaarvoice.com/2009-en_us/1061083288/reviews.djs?format=embeddedhtml&page=1&scrollToTop=true

    您可以轻松地自己为 bedbathandbeyond 上的每个产品构建此 URL,因为您只需要产品 id(在本例中为 1061083288)就可以轻松地从原始 DOM 中获取,例如使用 id 为 prodRatings 的 div。它包含一个带有产品 ID 的隐藏输入字段。然后,您可以简单地替换之前的 URL,这样您就可以从所有产品中获取所有评论。

    【讨论】:

    • 嗨,非常感谢您的回答,我明白了!所以问题不在于 JS 渲染对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 2013-05-30
    • 2021-05-02
    相关资源
    最近更新 更多