如何使用BeautifulSoup抓取亚马逊网页上的产品详情

0 投票
2 回答
9535 浏览
提问于 2025-04-30 22:55

对于这个网页:http://www.amazon.com/Harry-Potter-Prisoner-Azkaban-Rowling/dp/0439136369/ref=pd_sim_b_2?ie=UTF8&refRID=1MFBRAECGPMVZC5MJCWG,我想知道怎么用Python抓取产品的详细信息,并把这些信息输出成一个字典。

在这个例子中,我想要的字典输出是:

Age Range: 9 - 12 years
Grade Level: 4 - 7
...
...

我刚开始接触beautifulsoup,找不到好的例子来实现这个功能。我希望能有一些示例可以参考。

暂无标签

2 个回答

3
from bs4 import BeautifulSoup
import urllib
import urllib2
headers = {'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}
url = 'http://www.amazon.com/dp/0439136369'
data = urllib.urlencode(headers)
req = urllib2.Request(url,data)
soup = BeautifulSoup(urllib2.urlopen(req).read())
for x in soup.find_all('table',id='productDetailsTable'):
    for tag in x.find_all('li'):
        tag.get_text()

从上面的代码中,你可以提取表格里的文本。我没有把它格式化成打印输出或者放进字典里,因为你说你需要一点帮助。所以在上面的代码中,我做了这些事情。我需要把 user-agent 改一下,因为亚马逊不允许使用 python user-agent。我使用 find_all 方法来找到一个 id 为 'productDetailsTable' 的表格。然后我在这个表格里循环,寻找所有的 li 标签,因为所有的信息都存储在这些标签里。

2

这个想法是通过 table#productDetailsTable div.content ul li 这个 CSS选择器 来遍历所有的 Product Details 项目,然后把粗体文字当作键,把 下一个兄弟元素 当作值:

from pprint import pprint
from bs4 import BeautifulSoup
import requests

url = 'http://www.amazon.com/dp/0439136369'
response = requests.get(url, headers={'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'})

soup = BeautifulSoup(response.content)
tags = {}
for li in soup.select('table#productDetailsTable div.content ul li'):
    try:
        title = li.b
        key = title.text.strip().rstrip(':')
        value = title.next_sibling.strip()

        tags[key] = value
    except AttributeError:
        break

pprint(tags)

打印结果:

{
    u'Age Range': u'9 - 12 years',
    u'Amazon Best Sellers Rank': u'#1,440 in Books (',
    u'Average Customer Review': u'',
    u'Grade Level': u'4 - 7',
    u'ISBN-10': u'0439136369',
    u'ISBN-13': u'978-0439136365',
    u'Language': u'English',
    u'Lexile Measure': u'880L',
    u'Mass Market Paperback': u'448 pages',
    u'Product Dimensions': u'1.2 x 5.2 x 7.8 inches',
    u'Publisher': u'Scholastic Paperbacks (September 11, 2001)',
    u'Series': u'Harry Potter (Book 3)',
    u'Shipping Weight': u'11.2 ounces ('
}

注意,我们在遇到 AttributeError 的时候就会停止循环。这种情况发生在 li 元素里面没有更多的粗体文字时。

撰写回答