Urllib2的请求不起作用

时间:2015-03-22 20:35:29

标签: python python-2.7 web-scraping urllib2 python-requests

我有一个非常简单的示例,我认为requests应该毫无问题地替换urllib2。然而,似乎在最简单的情况下,我错过了一些东西。谁能告诉我为什么? (我想为我的GF获得makeup pricing))

from bs4 import BeautifulSoup
myurl = 'http://www.lancome-usa.com/skincare-cleanse/skincare-cleanse,default,sc.html'

# 1. urllib2
import urllib2
r = urllib2.urlopen(myurl)
soup = BeautifulSoup(r)
print 'MOUSSE RADIANCE' in soup.text.encode('utf-8').upper()
print '$32.00' in soup.text.encode('utf-8')

print '------------------------------------------------------'

# 2. requests
import requests
r = requests.get(myurl)
soup = BeautifulSoup(r.text)
print 'MOUSSE RADIANCE' in soup.text.encode('utf-8').upper()
print '$32.00' in soup.text.encode('utf-8')

响应:

True
True
------------------------------------------------------
False
False

最后,我升级了我的requests库,同时,我意识到使用r.text将无效。但是使用r.text.encode('utf-8')r.content将使用正确的内容构建汤。

1 个答案:

答案 0 :(得分:0)

您需要升级您的请求版本,您还可以获取"product-name"标记中的所有产品:

import requests
r = requests.get(myurl)
soup = BeautifulSoup(r.content)
products = {x.text.strip().lower() for x in soup.find_all("div",{"class":"product-name"})}

print("mousse radiance" in products)

for p in products:
    print(p)

True

crème radiance
crème douceur
absolue precious pure
mousse radiance
crème mousse confort
eau fraîche douceur
tonique confort
tonique pure focus
gel radiance

我正在使用2.5.3:

In [8]: import requests

In [9]: requests.__version__
Out[9]: '2.5.3'

您可以创建产品和价格的字典,这样您的女朋友就可以让您购买她的多种产品:

products = [x.text.strip().lower() for x in soup.find_all("div",{"class":"product-name"})]
prices = [x.text for x in soup.find_all("span",{"class":"product-sales-price"})]

items = dict(zip(products,prices))
print(items.get("mousse radiance","N/A"))
print(items)

$32.00
{u'cr\xe8me radiance': u'$25.00 - $37.00', u'cr\xe8me douceur': u'$25.00 - $37.00', u'absolue precious pure': u'$58.00', u'mousse radiance': u'$32.00', u'cr\xe8me mousse confort': u'$25.00', u'eau fra\xeeche douceur': u'$38.00 - $51.00', u'tonique confort': u'$25.00 - $44.00', u'tonique pure focus': u'$25.00', u'gel radiance': u'$25.00'}