如何使用beautifulsoup在亚马逊网页上搜索产品详细信息

时间:2014-10-31 20:18:40

标签: python web-scraping beautifulsoup scrape

对于网页:http://www.amazon.com/Harry-Potter-Prisoner-Azkaban-Rowling/dp/0439136369/ref=pd_sim_b_2?ie=UTF8&refRID=1MFBRAECGPMVZC5MJCWG 我怎么能在python中抓取产品细节并输出dict。 在上面的例子中,我想要的dict输出将是:

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

我是beautifulsoup的新手,并没有找到实现这一目标的好榜样。我希望有一些例子可以追随。

2 个答案:

答案 0 :(得分: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()

从上面的代码中你可以从表中提取文本,我没有将其格式化为打印或输入dict,正如你所说,你需要的帮助很少。所以我在上面的代码中做了什么。我需要更改user-agent,因为亚马逊不允许python user-agent。使用find_all  我找到了id=productDetailsTable'的表格。然后我循环查找所有li标签,因为所有信息都存储在此标签中。

答案 1 :(得分:2)

我们的想法是在Product Details CSS selector的帮助下迭代所有table#productDetailsTable div.content ul li项,然后使用粗体文本作为键,next sibling作为值:

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元素中没有更多粗体文本之后。

相关问题