【问题标题】:Flipkart.com product 'price' and product 'title' extraction using PythonFlipkart.com 使用 Python 提取产品“价格”和产品“标题”
【发布时间】:2013-04-29 01:26:06
【问题描述】:

我编写了以下 Python 代码来从flipkart.com 中提取指定项目的价格

import urllib2
import bs4
import re

item="Wilco Classic Library: Autobiography Of a Yogi (Hardcover)"
item.replace(" ", "+")
link = 'http://www.flipkart.com/search/a/all?query={0}&vertical=all&dd=0&autosuggest[as]=off&autosuggest[as-submittype]=entered&autosuggest[as-grouprank]=0&autosuggest[as-overallrank]=0&autosuggest[orig-query]=&autosuggest[as-shown]=off&Search=%C2%A0&otracker=start&_r=YSWdYULYzr4VBYklfpZRbw--&_l=pMHn9vNCOBi05LKC_PwHFQ--&ref=a2c6fadc-2e24-4412-be6a-ce02c9707310&selmitem=All+Categories'.format(item)
r = urllib2.Request(link, headers={"User-Agent": "Python-urlli~"})
try:
    response = urllib2.urlopen(r)
except:
    print "Internet connection error"  
thePage = response.read()
soup = bs4.BeautifulSoup(thePage)
firstBlockSoup = soup.find('div', attrs={'class': 'fk-srch-item'})
priceSoup=firstBlockSoup.find('b',attrs={'class':'fksd-bodytext price final-price'})
price=priceSoup.contents[0]
print price

titleSoup=firstBlockSoup.find('a',attrs={'class':'fk-srch-title-text fksd-bodytext'})
title=titleSoup.findAll('b')
print title

上面的代码在执行时打印 PRICE 没有问题。

Rs. 138 

但是标题是这样获取的:

[<b>Wilco</b>, <b>Classic</b>, <b>Library</b>, <b>Autobiography</b>, <b>Of</b>, <b>a</b>, <b>Yogi</b>, <b>Hardcover</b>] 

如果您查看product page 的源代码,原因就会很明显(使用“检查元素”)

现在,我如何以正确的格式提取 TITLE 以便打印:

Wilco Classic Library: Autobiography Of a Yogi (Hardcover)

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup


    【解决方案1】:

    只需在titleSoup 上使用text 方法

    >>> titleSoup=firstBlockSoup.find('a',attrs={'class':'fk-srch-title-text fksd-bodytext'})
    >>> titleSoup.text
    u'Wilco Classic Library: Autobiography Of a Yogi (Hardcover)'
    

    这也可以:

    invalid_tags = ['b']
    titleSoup=firstBlockSoup.find('a',attrs={'class':'fk-srch-title-text fksd-bodytext'})
    
    for tag in invalid_tags: 
        for match in titleSoup.findAll(tag):
           match.replaceWithChildren()
    print "".join(titleSoup.contents)
    

    【讨论】:

      【解决方案2】:

      firstBlockSoup标签中获取标题会更容易:

      >>> firstBlockSoup.attrs['data-item-name']
      'Wilco Classic Library: Autobiography Of a Yogi (Hardcover)'
      

      【讨论】:

      • 我使用您的代码加载了与您相同的 URL。你的titleSoup 元素为我返回了None
      • 这很奇怪。查看您的评论后,我执行了 10 次相同的代码。 titleSoup 元素有 10 次返回 None。对于这种行为,我想不出任何可能的解释。让我知道你是否知道。谢谢。
      猜你喜欢
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 2021-06-17
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多