我尝试使用 javascript 动态 + bs + python 进行网页抓取,并且我阅读了很多内容来编写此代码,例如,我尝试在著名网站上抓取使用 javascript 呈现的价格:
from bs4 import BeautifulSoup
from selenium import webdriver
url = "https://www.nespresso.com/fr/fr/order/capsules/original/"
browser = webdriver.PhantomJS(executable_path = "C:/phantomjs-2.1.1-windows/bin/phantomjs.exe")
browser.get(url)
html = browser.page_source
soup = BeautifulSoup(html, 'lxml')
soup.find("span", {'class':'ProductListElement__price'}).text
但我只有结果 '\xa0' 这是源值,而不是 javascript 值,我真的不知道我做错了什么......
致以诚挚的问候
最佳答案
您不需要购买浏览器。该信息位于脚本标记中,因此您可以使用正则表达式输出并使用 json 库进行处理
import requests, re, json
r = requests.get('https://www.nespresso.com/fr/fr/order/capsules/original/')
p = re.compile(r'window\.ui\.push\((.*ProductList.*)\)')
data = json.loads(p.findall(r.text)[0])
products = {product['name']:product['price'] for product in data['configuration']['eCommerceData']['products']}
print(products)
正则表达式:
关于Python、BS 和 Selenium,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59383669/