Python 3.x 在浏览网页时选择商店位置
我正在浏览一个杂货店网站()以便在购物前做一些膳食计划。产品的价格因商店的位置而异。我想从我当地的商店(奥尔巴尼)中提取价格 我不熟悉网页抓取,但我认为我的代码必须Python 3.x 在浏览网页时选择商店位置,python-3.x,web-scraping,beautifulsoup,python-requests,Python 3.x,Web Scraping,Beautifulsoup,Python Requests,我正在浏览一个杂货店网站()以便在购物前做一些膳食计划。产品的价格因商店的位置而异。我想从我当地的商店(奥尔巴尼)中提取价格 我不熟悉网页抓取,但我认为我的代码必须 将默认存储更改为我的本地存储(Albany,使用此url:) 维护一个请求“会话”,以确保我从同一门店网站上刮取所有产品 我的刮码成功地刮取了西兰花的价格,但价格与我当地商店的价格不一致。在发布我的花椰菜价格时,我的价格是1.99美元,但当我在奥尔巴尼商店手工检查价格时,价格是0.99美元。 我假设切换到正确存储的代码没有按预期工作
- 请求==2.23.0
- beautifulsoup4==4.6.3
- Python 3.7.10
import requests
from bs4 import BeautifulSoup as bs
import re
dollars_pattern = '>([0-9][0-9]?)'
cents_pattern = '>([0-9][0-9])'
url = 'https://www.paknsaveonline.co.nz/CommonApi/Store/ChangeStore?storeId=65defcf2-bc15-490e-a84f-1f13b769cd22'
header = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36", "X-Requested-With": "XMLHttpRequest"} }
with requests.session() as s:
#I assume this url changes the store (200 response)
s.get(url)
#use the same session to return broccoli price
r = s.get('https://www.paknsaveonline.co.nz/product/5039956_ea_000pns?name=broccoli')
soup = bs(r.content,'html.parser')
cents = str(soup.find_all('span', {'class': "fs-price-lockup__cents"}))
dollars = str(soup.find_all('span', {'class': "fs-price-lockup__dollars"}))
centsprice =re.findall(cents_pattern, cents)
dollarsprice = re.findall(dollars_pattern, dollars)
print(dollarsprice, centsprice)
当我看到实际的请求时,您需要首先从基本URL获取一些cookie,然后您可以为该会话更改存储,您不能通过调用该URL直接修改存储,因此首先调用基本URL,然后更改存储URL,然后再次调用基本URL以获取
0.99
美分的价格
import requests
from bs4 import BeautifulSoup as bs
import re
dollars_pattern = '>([0-9][0-9]?)'
cents_pattern = '>([0-9][0-9])'
url = 'https://www.paknsaveonline.co.nz/CommonApi/Store/ChangeStore?storeId=65defcf2-bc15-490e-a84f-1f13b769cd22'
baseurl="https://www.paknsaveonline.co.nz/product/5039956_ea_000pns?name=broccoli"
header = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
"X-Requested-With": "XMLHttpRequest"
}
with requests.session() as s:
#I assume this url changes the store (200 response)
s.get(baseurl)
s.get(url)
#use the same session to return broccoli price
r = s.get(baseurl)
soup = bs(r.content,'html.parser')
cents = str(soup.find_all('span', {'class': "fs-price-lockup__cents"}))
dollars = str(soup.find_all('span', {'class': "fs-price-lockup__dollars"}))
centsprice =re.findall(cents_pattern, cents)
dollarsprice = re.findall(dollars_pattern, dollars)
print(dollarsprice, centsprice)
如果您有任何问题,请告诉我:)很好,都经过测试,可以根据需要工作