I'm trying to capture price from amazon based on xpath but if else statement is not working correctly - can someone please help to solve the issue? if 1st xpath didn't find the eliment then it will find through 2nd xpath
from bs4 import BeautifulSoup
from lxml import etree
import requests
HEADERS = ({'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0','Accept-Language': 'en-US, en;q=0.5'})
URL= "https://www.amazon.in/dp/B099Z83VRC"
webpage = requests.get(URL, headers=HEADERS)
soup = BeautifulSoup(webpage.content, "lxml")
dom = etree.HTML(str(soup))
Price = dom.xpath('//div[@id="apex_desktop"]/div/div/span/span/text()')[0]
if Price == AttributeError:
Price = dom.xpath('//div[@id="apex_desktop"]/div/div/table//tr[2]/td[2]/span/span[1]/text()')[0]
else:
Price = "No data"
Price
CodePudding user response:
You can use try..except block if it throws error for the first xpath
it will go except block and try with second one.
try:
Price = dom.xpath('//div[@id="apex_desktop"]/div/div/span/span/text()')[0]
except:
Price = dom.xpath('//div[@id="apex_desktop"]/div/div/table//tr[2]/td[2]/span/span[1]/text()')[0]
print(Price)