使用Python和bs4进行Walmart.com价格限价

时间:2018-09-02 02:28:46

标签: python python-3.x python-2.7 python-requests

我正在尝试从沃尔玛上的某个页面抓取价格,但出现错误。下面是我的代码:

import requests
from bs4 import BeautifulSoup

URL = "https://www.walmart.com/ip/Wilson-The-Duke-Official-NFL-Game-Football/5192758"
page = requests.get(URL,headers={"User-Agent":"Defined"})
soup = BeautifulSoup(page.content, "html.parser")
price = soup.find(id="price-group").get_text()
print(price)

我在命令行上得到以下输出:

  

回溯(最近通话最近):     在第7行中输入文件“ walmart.py”       price = soup.find(id =“ price-group”)。get_text()   AttributeError:“ NoneType”对象没有属性“ get_text”

对于Nordstorm和Sears,我看到了类似的错误。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

我查看了给定的URL,并且价格组似乎是类名而不是ID。所以你需要:

price = soup.find(class_="price-group").get_text()

答案 1 :(得分:0)

在使用 beautifulsoup 时,它向我抛出了一个错误。如果发生这种情况,另一种方法是使用 requests-htmlselenium 来呈现页面或提升浏览器。

代码:

from requests_html import HTMLSession

session = HTMLSession()
response = session.get('https://www.walmart.com/ip/Wilson-The-Duke-Official-NFL-Game-Football/5192758')

title = response.html.find('.prod-productTitle-buyBox', first=True).text
price = response.html.find('.prod-PriceHero', first=True).text.split('$')[1]
print(f'{title}\n{price}')

# Output:
'''
Wilson "The Duke" NFL Official Game Football
119.95
'''

本质上,您可以使用来自 SerpApi 的 Walmart Product Result API 做同样的事情,除了在本例中,您不必弄清楚如何获取 HTML 页面的某些元素或如何避免阻塞发生。这是一个付费 API,可免费试用 5,000 次搜索。

要集成的代码:

from serpapi import GoogleSearch

params = {
  "api_key": "YOUR_API_KEY",
  "engine": "walmart_product",
  "product_id": "5192758"
}

search = GoogleSearch(params)
results = search.get_dict()

title = results['product_result']['title']
price = results['product_result']['price_map']['price']

print(f'{title}\n{price}')

# Output:
'''
Wilson "The Duke" NFL Official Game Football
119.95
'''
<块引用>

免责声明,我为 SerpApi 工作。