如何使用延迟加载下载页面?

How to download a page with lazy loading?

我需要下载整页并解析它,但它在 JavaScript 的帮助下创建了一些元素。当我尝试在 urllib 的帮助下执行此操作时,我收到一个没有使用 JavaScript 元素的 html 页面。我该如何解决这个问题?

import urllib.request as urlib

page = urlib.urlopen('https://www.example.com')
soup = BeautifulSoup(page, 'html5lib')
...

正在尝试:

colordiv = soup.select("div.pswp__item:nth-child(1) > div:nth-child(1) > img:nth-child(1)'")[0]

与:

https://www.electrictobacconist.com/smok-nord-p5831

您可以使用开发工具找到用于更新颜色值的请求

import requests

r = requests.get('https://www.electrictobacconist.com/ajax/get_product_options/5831').json()
colours = [item['value'] for item in r['attributes'][0]['values']]
print(colours)

即使页面是使用 JavaScript 呈现的,数据也是通过后台的 ajax 响应接收的。您所要做的就是提出该请求。

import requests
import re
url='https://www.electrictobacconist.com/smok-nord-p5831'
#get 5831
product_id=re.findall(r'\d+', url)[-1]
r=requests.get("https://www.electrictobacconist.com/ajax/get_product_options/{}".format(product_id))
print([x['value'] for x in r.json()['attributes'][0]['values']])

输出:

['Black/Blue', 'Black/White', 'Bottle Green', 'Full Black', 'Prism Gold', 'Prism Rainbow', 'Red', 'Resin Rainbow', 'Yellow/Purple', 'Blue/Brown', 'Red/Yellow', 'Red/Green', 'Black/White Resin']