【发布时间】:2021-07-23 15:23:46
【问题描述】:
我正在尝试使用 requests 模块从 webpage 中抓取两个字段 product_title 和 item_code。当我执行下面的脚本时,我总是得到AttributeError 来代替结果,因为我所追求的数据不在页面源中。
但是,我在这里遇到了几种解决方案,即使数据不在页面源中,它们也能够从 javascript 加密站点获取数据,所以我想应该有任何方法可以从网页中获取这两个字段使用请求。
import requests
from bs4 import BeautifulSoup
link = 'https://www.sainsburys.co.uk/gol-ui/Product/persil-small---mighty-non-bio-laundry-liquid-21l-60-washes'
with requests.Session() as s:
s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
res = s.get(link)
soup = BeautifulSoup(res.text,"lxml")
product_title = soup.select_one("h1[data-test-id='pd-product-title']").get_text(strip=True)
item_code = soup.select_one("span#productSKU").get_text(strip=True)
print(product_title,item_code)
预期输出:
Persil Non-Bio Laundry Liquid 1.43L
Item code: 7637944
如何使用请求从该站点获取这两个字段?
【问题讨论】:
标签: python python-3.x web-scraping python-requests