Python 使用正则表达式或其他方法捕获网站数据
我试图使用python和regex在下面的示例网站中降低价格,但没有得到任何结果 我如何才能最好地捕捉价格(我不在乎分钱,只在乎美元金额) 相关HTML:Python 使用正则表达式或其他方法捕获网站数据,python,html,regex,web-scraping,Python,Html,Regex,Web Scraping,我试图使用python和regex在下面的示例网站中降低价格,但没有得到任何结果 我如何才能最好地捕捉价格(我不在乎分钱,只在乎美元金额) 相关HTML: <div class="price-display csTile-price"> <span class="sup">$</span> 299 <span class="currency-delimiter">.</span>
<div class="price-display csTile-price">
<span class="sup">$</span>
299
<span class="currency-delimiter">.</span>
<span class="sup">00</span>
</div>
$
299
.
00
正则表达式是什么来捕获“299”的,或者是更容易获得它的方法?谢谢 使用regexp,您的模式应该有多精确可能有点棘手。 我很快在这里输入了一些内容: 你应该了解这个想法,并根据你的实际需要修改这个想法
亲切问候不要使用正则表达式使用html解析器,如: 或者使用
货币分隔符
span并获取上一个元素:
amount = soup.select_one("span.currency-delimiter").previous.strip()
这会给你同样的结果。您的问题中的html也是通过Javascript动态生成的,因此您不会使用urllib.urlopen
获得它,它根本不在返回的源代码中
您将需要像selenium这样的东西,或者像下面那样使用模拟ajax调用
这给了您一些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}
这就为您提供了所需的所有信息,您所做的只是将url中的参数和门店号发布到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
好的,只需搜索数字(我添加了$and.)并将结果合并成字符串(我使用了“.join())
>>txt=”“”
$
299
.
00
"""
>>>'.join(关于findall('[0-9$.]',txt.replace(“\n”,”))
'$299.00'
您能展示一下您尝试了什么以及得到了什么结果吗?大多数人都使用类似于流行语法的语法分析器。你可以在网上找到很多教程或问题。哇-你太快了!!我需要一些时间来消化。目前我有这个,它还没有抢到价格。似乎我应该修补bs4…@MiaElla,urllopen不会提供您需要的源代码,右键单击您的浏览并选择查看源代码,您将不会在任何地方看到问题中的html。它是通过javascript加载的。您需要使用selenium之类的东西来处理javascript,或者使用我使用请求所做的事情。我会使用请求逻辑复制您的json输出,但在如何实现“获取价格和名称:”部分时迷失了方向。我的另一个目标是遍历存储列表,并按存储输出结果。有什么想法吗?很明显,我还在学习,很抱歉我理解得太慢了。price=res[“price”][“priceInCents”/100
如果使用python2,你也想要分钱,name=res[“name”])
,显然是在data=json.loads(js['searchResults')
和res=data[“results”][0]
,基本上只需按照答案中的步骤操作。有一种类型,name=res[“name”]
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)
{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}
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
>>> 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'