我编写了一个 python 程序来从几个购物网站上抓取数据,直到最近,该程序在这两个网站上都运行良好。
URL2 - https://www.Continente.pt/produto/papa-infantil-farinha-lactea-6m-cerelac-2004388.html
我使用以下简单代码:
import requests
from bs4 import BeautifulSoup
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
# ... and then i have my code to parse stuff...
问题是:在 URL1 上,一切都很好,而且如果我打印(汤),我会使用浏览器获得页面源代码中看到的页面 HTML。但是在 URL2 上,我得到的似乎是脚本代码(请参阅附图),当然我的解析代码会失败,因为它找不到元素。如果我在浏览器上打开网页,看起来不错,并且可以按预期查看源代码。
我显然是一个新手,但似乎有某种防止报废的保护措施;有什么我可以做的吗?
谢谢!
你看到的“脚本语言”是最小化的JS。我假设它向 Continente 的中央服务器发出请求,然后填充页面。最简单的方法是使用
chromedriver
来执行代码并填充页面,其功能几乎与浏览器相同。
from selenium import webdriver
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
driver.get("https://www.continente.pt/produto/papa-infantil-farinha-lactea-6m-cerelac-2004388.html")
soup = BeautifulSoup(driver.page_source, "html.parser")
# ...