我正在使用python 2.7和Beautiful Soup的4.5.1版
我在我的智慧结束时试图让这个非常简单的脚本工作。我的目标是通过解析产品页面的html并在
中提取信息,从Best Buy的网站获取有关NES控制台在线可用性状态的信息。<div class="status online-availability-status"> Sold out online </div>
这是我第一次使用Beautiful Soup模块,如果我错过了一些明显的东西,请原谅我。这是我写的脚本,试图获取上述信息:
import requests
from bs4 import BeautifulSoup
page = requests.get('http://www.bestbuy.ca/en-CA/product/nintendo-nintendo-entertainment-system-nes-classic-edition-console-clvsnesa/10488665.aspx?path=922de2a5ceb066b0f058cc567ad3d547en02')
soup = BeautifulSoup(page.content, 'html.parser')
avail = soup.findAll('div', {"class": "status online-availability-status"})
但是我只得到avail
的空列表。知道为什么吗?
非常感谢任何帮助。
答案 0 :(得分:1)
正如上面的评论所示,您似乎正在寻找一个由JavaScript生成的客户端标记;它显示在加载的页面上使用'inspect',但在查看页面源时不显示,这是对请求的调用正在撤回的内容。您可以尝试使用dryscrape(您可能需要使用pip install dryscrape
安装)。
import dryscrape
from bs4 import BeautifulSoup
session = dryscrape.Session()
url = 'http://www.bestbuy.ca/en-CA/product/nintendo-nintendo-entertainment-system-nes-classic-edition-console-clvsnesa/10488665.aspx?path=922de2a5ceb066b0f058cc567ad3d547en02'
session.visit(url)
response = session.body()
soup = BeautifulSoup(response)
avail = soup.findAll('div', {"class": "status online-availability-status"})
这是有关抓取动态生成内容的问题中最受欢迎的解决方案:
答案 1 :(得分:0)
可用性以JSON格式加载。您甚至不需要为此解析HTML:
import urllib
import simplejson
sku = 1048865 # look at the URL of the web page, it is <blablah>//10488665.aspx
# chnage locations to get the right store
response = urllib.urlopen('http://api.bestbuy.ca/availability/products?callback=apiAvailability&accept-language=en&skus=%s&accept=application%2Fvnd.bestbuy.standardproduct.v1%2Bjson&postalCode=M5G2C3&locations=977%7C203%7C931%7C62%7C617&maxlos=3'%sku)
availability = simplejson.loads(response.read())
print availability[0]['shipping']['status']
答案 2 :(得分:0)
如果您尝试打印 soup
,您会看到它可能返回类似 Access Denied
的内容。这是因为 Best Buy 需要一个允许的 User-Agent
才能发出 GET 请求。由于您没有在 Header 中指定 User-Agent,因此它不会返回任何内容。
这是生成用户代理的链接 How to use Python requests to fake a browser visit a.k.a and generate User Agent?
或者您可以找出在您自己的浏览器中查看网页时生成的用户代理 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent