【问题标题】:BeautifulSoup gives unexpected resultsBeautifulSoup 给出了意想不到的结果
【发布时间】:2019-05-19 21:11:40
【问题描述】:

我是网络抓取领域的新手,在运行以下代码时,我得到了意想不到的结果:

from bs4 import BeautifulSoup as soup
import requests

header = {'User-Agent':'Chrome/71.0.3578.98 Mozilla/64.0'}
url = 'https://www.amazon.in/Philips-Trimmer-Cordless-QT4001-15/dp/B00L8PEEAI'
res = requests.get(url, headers = header)
bs = soup(res.text, 'html.parser')
print(bs.div)

产生以下输出:

<!-- From remote config v3-->
<script type="text/javascript">
    (function(d) {
        document.createElement("header");

        function b(e) {
            return [].slice.call(e)
        }

        function c(f, e) {
            return {
                m: f,
                a: b(e)
            }
        }
        var a = function(f) {
            var g = {};
            g._sourceName = f;
            g._replay = [];
            g.getNow = function(i, h) {
                return h
            };

            function e(i, h, j) {
                i[j] = function() {
                    g._replay.push(h.concat(c(j, arguments)))
                }
            }
            g.when = function() {
                var i = [c("when", arguments)];
                var h = {};
                e(h, i, "run");
                e(h, i, "declare");
                e(h, i, "publish");
                e(h, i, "build");
                return h
            };
            e(g, [], "declare");
            e(g, [], "build");
            e(g, [], "publish");
            e(g, [], "importEvent");
            a._shims.push(g);
            return g
        };
        a._shims = [];
        if (!d.$Nav) {
            d.$Nav = a("rcx-nav")
        }
        if (!d.$Nav.make) {
            d.$Nav.make = a
        }
    }(window));

这显然不是我想要的。而且我无法使用它,例如,如果我需要获取产品名称,我会写如下内容:

bs.findAll("div",{"id":"titleSection"})[0].span.text.strip()

哪个,给定上面的输出会引发索引错误。奇怪的是,当我通过一个循环在终端上针对亚马逊上的几个类似产品运行此代码时,它对前 10-15 个产品运行良好,然后抛出相同的错误,有时在分解之前会达到 130 个项目,在其他情况下在第一次迭代时给出错误。对于这种随机行为的解释(可能还有解决方案),我将非常感谢。

【问题讨论】:

    标签: python-3.x beautifulsoup python-requests


    【解决方案1】:

    resquests 无法提取带有 javascript 渲染的页面,因此要解决问题,您可以选择:

    1. 使用 selenium、splash 或 html-requests 来呈现 javascript;
    2. 使用浏览器的请求和网络工具获取json文件。

    【讨论】:

    • html-requests package 是另一个选项,用于在解析之前呈现页面
    • 我尝试在selenium下使用PhantomJS webdriver,但问题依旧
    • Phantom.js 已弃用,请使用带有 selenium 的 chrome 驱动程序。
    猜你喜欢
    • 2017-01-05
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2021-04-22
    • 2016-02-13
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多