如何使用 BeautifulSoup 在 Amazon.com 上抓取新格式的产品信息?

How to scrape the new format for Product information on Amazon.com using BeautifulSoup?

在此 post 中,alecxe 给出了如何抓取 Amazon.com 产品 information/Product 详细信息 table 的解决方案。但是,该描述的格式 table 与亚马逊上列出的许多新商品不同。

旧格式,你可以看到here, is different than the new format here

我试过的:在他使用的alecxe给出的代码中

for li in soup.select('table#productDetailsTable div.content ul li'):

我尝试将其更改为(并删除了它之后的所有内容):

for tr in soup.select('table#productDetails_detailBullets_sections1 tbody tr'):
    print text.tr
    print(repr(tr))

看看我是否能够至少从产品信息中提取一些东西 table。但是,没有打印任何内容。

我也尝试了 find_all()find() 函数,但我无法提取我需要的东西,甚至无法接近我需要的东西。

我解决这个问题的原因是新 table 的 HTML 的结构。它看起来像:

<table ... >
<tbody>
.
.
.    
<tr>
    <th class="a-color-secondary a-size-base prodDetSectionEntry">
        Best Sellers Rank
    </th>
    <td>
         <span>

                <span>#8,740 in Toys &amp; Games (<a href="/gp/bestsellers/toys-and-games/ref=pd_dp_ts_toys-and-games_1">See Top 100 in Toys &amp; Games</a>)</span>
        <br>

                <span>#67 in <a href="/gp/bestsellers/toys-and-games/ref=pd_zg_hrsr_toys-and-games_1_1">Toys &amp; Games</a> &gt; <a href="/gp/bestsellers/toys-and-games/166359011/ref=pd_zg_hrsr_toys-and-games_1_2">Puzzles</a> &gt; <a href="/gp/bestsellers/toys-and-games/166363011/ref=pd_zg_hrsr_toys-and-games_1_3_last">Jigsaw Puzzles</a></span>
        <br>

                <span>#87 in <a href="/gp/bestsellers/toys-and-games/ref=pd_zg_hrsr_toys-and-games_2_1">Toys &amp; Games</a> &gt; <a href="/gp/bestsellers/toys-and-games/251909011/ref=pd_zg_hrsr_toys-and-games_2_2">Preschool</a> &gt; <a href="/gp/bestsellers/toys-and-games/251910011/ref=pd_zg_hrsr_toys-and-games_2_3">Pre-Kindergarten Toys</a> &gt; <a href="/gp/bestsellers/toys-and-games/251942011/ref=pd_zg_hrsr_toys-and-games_2_4_last">Puzzles</a></span>
        <br>

        </span>
    </td>
    </tr>
.
. 
.
</tbody>
</table>

如果我只想提取 "Toys & Games > Puzzles > Jigsaw Puzzles" 的卖家排名,我应该怎么做? (第二个中的文字,至少在这种情况下,在HTML上面)

我可以通过一些小的调整让您的代码工作:

  1. 去掉soup.select中的'tbody',这是浏览器生成的标签
  2. 打印 tr.text 而不是 text.tr

代码:

for tr in soup.select('table#productDetails_detailBullets_sections1 tr'):
    if 'Jigsaw Puzzles' in tr.text :
        print(tr.text.strip())

或者如果您更喜欢 find / find_all

for tr in soup.find('table', id='productDetails_detailBullets_sections1').find_all('tr') :
    if 'Jigsaw Puzzles' in tr.text : 
        for span in tr.find('span').find_all('span') : 
            if 'Jigsaw Puzzles' in span.text : 
                print(span.text.strip())