当我试图从以下网站抓取数据时
我是从 bedbathbeyond 网站上得到的,如果我使用 request 和 beautifulsoup,我什么也得不到。这是为什么?
代码:
r = requests.get(url)
soup = BeautifulSoup(r.content,'lxml')
soup.find_all('span', class_ = 'BVRRReviewAbbreviatedText')
返回值为空:[]
请您参考如下方法:
我用了js2py ,因为 materials 对象包含多个键(BVRRRatingSummarySourceID、BVRRSecondaryRatingSummarySourceID 和 BVRRSourceID)并从其值中获取 HTML正则表达式会更难,以防您需要它。
from bs4 import BeautifulSoup
import js2py
import requests
r = requests.get('https://bedbathandbeyond.ugc.bazaarvoice.com/2009-en_us/1061083288/reviews.djs?format=embeddedhtml')
pattern = (r'var'
r'\s+'
r'materials'
r'\s*=\s*'
r'{"BVRRRatingSummarySourceID".*}')
js_materials = re.search(pattern, r.text).group()
obj = js2py.eval_js(js_materials).to_dict()
html = obj['BVRRSourceID']
soup = BeautifulSoup(html, 'lxml')
spans = soup.select('span.BVRRReviewAbbreviatedText')
>>> len(spans)
5
在下面的示例中,我只使用了 BVRRSourceID 键下的 HTML,但您可以通过将这些值连接在一起来使用整个 HTML:
html = ''.join(obj.values())
不要忘记安装 js2py:pip install js2py 和 pip install lxml 如果你想使用 lxml解析器。
