繁体   English   中英

使用正则表达式或其他内容捕获网站数据

[英]Use regex or something else to capture website data

我正在尝试使用python和regex在下面的示例网站中拉价格,但没有得到任何结果。

如何最好地把握价格(我不在乎美分,仅在乎美元金额)?

http://www.walmart.com/store/2516/search?dept=4044&dept_name=Home&query=43888060

相关HTML:

<div class="price-display csTile-price">
       <span class="sup">$</span>
       299
       <span class="currency-delimiter">.</span>
       <span class="sup">00</span>
</div>

捕获“ 299”的正则表达式是什么,或者更容易获得它的途径? 谢谢!

使用regexp,您的模式应达到的精度可能会有些棘手。 我很快在这里输入了一些内容: https : //regex101.com/r/lF5vF2/1

您应该了解并修改此想法以适合您的实际需求。

亲切的问候

不要使用正则表达式使用bs4之类的html解析器:

from bs4 import BeautifulSoup
h = """<div class="price-display csTile-price">
       <span class="sup">$</span>
       299
       <span class="currency-delimiter">.</span>
       <span class="sup">00</span>
</div>"""
soup = BeautifulSoup(h)

amount = soup.select_one("div.price-display.csTile-price span.sup").next_sibling.strip()

这会给你:

299

或使用currency-delimiter span并获取上一个元素:

amount = soup.select_one("span.currency-delimiter").previous.strip()

这将给您相同。 您问题中的html也是通过Javascript 动态生成的 ,因此您不会使用urllib.urlopen来获取它,只是不在返回的源中。

您将需要类似selenium之类的东西,或使用请求模仿ajax调用,如下所示。

import requests
import json
js = requests.post("http://www.walmart.com/store/ajax/search",
                    data={"searchQuery":"store=2516&size=18&dept=4044&query=43888060"} ).json()

data = json.loads(js['searchResults'])

from pprint import pprint as pp
pp(data)

那给了你一些json:

{u'algo': u'polaris',
 u'blacklist': False,
 u'cluster': {u'apiserver': {u'hostname': u'dfw-iss-api8.stg0',
                             u'pluginVersion': u'2.3.0'},
              u'searchengine': {u'hostname': u'dfw-iss-esd.stg0.mobile.walmart.com'}},
 u'count': 1,
 u'offset': 0,
 u'performance': {u'enrichment': {u'inventory': 70}},
 u'query': {u'actualQuery': u'43888060',
            u'originalQuery': u'43888060',
            u'suggestedQueries': []},
 u'queryTime': 181,
 u'results': [{u'department': {u'name': u'Home', u'storeDeptId': -1},
               u'images': {u'largeUrl': u'http://i5.walmartimages.com/asr/7b8fd3b1-8eed-4b68-971b-81188ddb238c_1.a181800cade4db9d42659e72fa31469e.jpeg?odnHeight=180&odnWidth=180',
                           u'thumbnailUrl': u'http://i5.walmartimages.com/asr/7b8fd3b1-8eed-4b68-971b-81188ddb238c_1.a181800cade4db9d42659e72fa31469e.jpeg?odnHeight=180&odnWidth=180'},
               u'inventory': {u'isRealTime': True,
                              u'quantity': 1,
                              u'status': u'In Stock'},
               u'isWWWItem': True,
               u'location': {u'aisle': [], u'detailed': []},
               u'name': u'Dyson Ball Multi-Floor Bagless Upright Vacuum, 206900-01',
               u'price': {u'currencyUnit': u'USD',
                          u'isRealTime': True,
                          u'priceInCents': 29900},
               u'productId': {u'WWWItemId': u'43888060',
                              u'productId': u'2FY1C7B7RMM4',
                              u'upc': u'88560900430'},
               u'ratings': {u'rating': u'4.721',
                            u'ratingUrl': u'http://i2.walmartimages.com/i/CustRating/4_7.gif'},
               u'reviews': {u'reviewCount': u'1436'},
               u'score': u'0.507073'}],
 u'totalCount': 1}

这样就可以为dict提供您可能需要的所有信息,您要做的就是将参数和商店编号发布到http://www.walmart.com/store/ajax/search

获取价格和名称:

In [22]: import requests

In [23]: import json

In [24]: js = requests.post("http://www.walmart.com/store/ajax/search",
   ....:                     data={"searchQuery":"store=2516&size=18&dept=4044&query=43888060"} ).json()

In [25]: data = json.loads(js['searchResults'])

In [26]: res = data["results"][0]

In [27]: print(res["name"])
Dyson Ball Multi-Floor Bagless Upright Vacuum, 206900-01

In [28]: print(res["price"])
{u'priceInCents': 29900, u'isRealTime': True, u'currencyUnit': u'USD'}
In [29]: print(res["price"]["priceInCents"])
29900

In [30]: print(res["price"]["priceInCents"]) / 100
299

好的,只需搜索数字(我添加了$和。),然后将结果合并为字符串(我使用了““ .join())。

>>> txt = """
      <div class="price-display csTile-price">
          <span class="sup">$</span>
            299
          <span class="currency-delimiter">.</span>
          <span class="sup">00</span>
      </div>
      """


>>> ''.join(re.findall('[0-9$.]',txt.replace("\n","")))
'$299.00'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM