1
votes

So I have this code which should get the price of any item on Amazon. However, instead of getting a price, I get an empty list.

from lxml import html
import requests

page = requests.get('https://www.amazon.com/gp/product/B06XP634L1?pf_rd_p=183f5289-9dc0-416f-942e-e8f213ef368b&pf_rd_r=W4XQCYJ4N9VQGF8HDAH0')
doc = html.fromstring(page.content)
price = doc.xpath("//span[@id='priceblock_ourprice']")
print(price)

This was working for me before. I would appreciate any help. Thanks in advance.

1
use wget or curl (or, if you are on Windows, Invoke-Webrequest in Powershell) to download the URL. Look into the resulting HTML code. Is the <span> you want in there? If no, then you will never find it with requests.get() and XPath, either, because it is created by Javascript after the page load. - Tomalak

1 Answers

0
votes

You need to add a User-Agent header

from lxml import html
import requests

headers = {'User-Agent':'Mozilla\5.0'}
page = requests.get('https://www.amazon.com/gp/product/B06XP634L1?pf_rd_p=183f5289-9dc0-416f-942e-e8f213ef368b&pf_rd_r=W4XQCYJ4N9VQGF8HDAH0', headers = headers)
doc = html.fromstring(page.content)
price = doc.xpath("//span[@id='priceblock_ourprice']")
print(price[0].text)

Or

price = doc.xpath("//span[@id='priceblock_ourprice']/text()")
print(price)

bs4

from bs4 import BeautifulSoup as bs
import requests

headers = {'User-Agent':'Mozilla\5.0'}
page = requests.get('https://www.amazon.com/gp/product/B06XP634L1?pf_rd_p=183f5289-9dc0-416f-942e-e8f213ef368b&pf_rd_r=W4XQCYJ4N9VQGF8HDAH0', headers = headers)
soup = bs(page.content, 'lxml')
price = soup.select_one("#attach-base-product-price")['value']
print(price)