In beautiful soup, how do I retrieve a nested element?
Below I am trying to retrieve the name of the product which is: LAP 13A 2-Gang SP Switched Socket + 3.1A 2-Outlet Type A USB Charger White
<h1 id="product_description" tabindex="0">
<span itemprop="name">
LAP 13A 2-Gang SP Switched Socket + 3.1A 2-Outlet Type A USB Charger White
</span>
<span class="sm" id="product_code_container">
(<span itemprop="productID">4087P</span>)
<meta itemprop="sku" content="4087P">
</span>
</h1>
I have tried the code below but doesn't return any product names, just blank:
soup = bs(page.content, 'html.parser')
product_title = soup.find('h1',attrs={'id':'product_description'}).find('span', attrs={'itemprop':'name'})
products.append(product_title.text)
from bs4 import BeautifulSoup
import requests
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'
}
res=requests.get("https://www.screwfix.com/p/lap-13a-2-gang-sp-switched-socket-3-1a-2-outlet-type-a-usb-charger-white/4087p",headers=headers)
soup=BeautifulSoup(res.text,"html.parser")
title=soup.find("h1",attrs={"id":"product_description"}).get_text(strip=True)
Output:
'LAP 13A 2-Gang SP Switched Socket + 3.1A 2-Outlet Type A USB Charger White(4087P)'
2nd method:
you can try to print soup and from different tags you can find title ex. i have found title from p
tag.
p_tag=soup.find("p",attrs={"class":"pdp-float-cta__title"})
p_tag.get("title")
output:
'LAP 13A 2-Gang SP Switched Socket + 3.1A 2-Outlet Type A USB Charger White'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.