【问题标题】:IndexError: list index out of range while using bs4IndexError:使用 bs4 时列表索引超出范围
【发布时间】:2016-06-20 22:03:24
【问题描述】:

这是我试图获取数据的链接flipkart

以及代码部分:

   <div class="toolbar-wrap line section">
   <div class="ratings-reviews-wrap">
      <div itemprop="aggregateRating" itemscope="" itemtype="http://schema.org/AggregateRating" class="ratings-reviews line omniture-field">
         <div class="ratings">
            <meta itemprop="ratingValue" content="1">
            <div class="fk-stars" title="1 stars">
               <span class="unfilled">★★★★★</span>
               <span class="rating filled" style="width:20%">
               ★★★★★
               </span>
            </div>
            <div class="count">
               <span itemprop="ratingCount">2</span>
            </div>
         </div>
      </div>

  </div>

</div>

这里我必须从 title= 1 star 获取 1 颗星,从 &lt;span itemprop="ratingCount"&gt;2&lt;/span&gt; 获取 2 颗星

我试试下面的代码

 x = link_soup.find_all("div",class_='fk-stars')[0].get('title')

 print x, " product_star"
 y = link_soup.find_all("span",itemprop="ratingCount")[0].string.strip()
 print y

但它给了

IndexError: 列表索引超出范围

【问题讨论】:

标签: python python-2.7 urllib2 bs4


【解决方案1】:

您在浏览器中看到的内容实际上并不存在于从this URL 检索到的原始 HTML 中。

当使用浏览器加载时,页面会执行 AJAX 调用以加载其他内容,然后将其动态插入到页面中。其中一个电话会获取您所追求的收视率信息。具体来说,this URL 是包含作为“操作栏”插入的 HTML 的那个。

但是,如果您使用 Python 检索主页,例如与requestsurllib 等。 al.,动态内容没有加载,这就是 BeautifulSoup 找不到标签的原因。

您可以分析主页以找到实际链接,检索该链接,然后通过 BeautifulSoup 运行它。该链接看起来以/p/pv1/spotList1/spot1/actionBar 开头,因此,或者actionBar 足以找到实际链接。

或者您可以使用selenium 加载页面,然后抓取并处理呈现的 HTML。

【讨论】:

    猜你喜欢
    • 2011-10-31
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多