我是Beautiful Soup和Python的新手,但我的问题是如何指定一个动态的类(productId)?我可以使用面具或搜索课程的一部分,即"产品摘要*"
<li class="product_summary clearfix {productId: 247559}">
</li>
我想在product_summary类列表下面获取product_info和product_image(src)数据,但是当我的类是动态的时候,我不知道如何find_all。希望这是有道理的。我的目标是将这些数据插入到MySQL表中,所以我的想法是我需要将所有数据存储到最高(产品摘要)级别的变量中。提前感谢您的帮助。
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
url = Request('http://www.shopwell.com/sodas/c/22', headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(url).read()
soup = BeautifulSoup(webpage)
product_info = soup.find_all("div", {"class": "product_info"})
for item in product_info:
detail_link = item.find("a", {"class": "detail_link"}).text
try:
detail_link_h2 = ""
detail_link_h2 = item.h2.text.replace("\n", "")
except:
pass
try:
detail_link_h3 = ""
detail_link_h3 = item.h3.text.replace("\n", "")
except:
pass
try:
detail_link_h4 = item.h4.text.replace("\n", "")
except:
pass
print(detail_link_h2 + ", " + detail_link_h3 + ", " + detail_link_h4)
product_image = soup.find_all("div", {"class": "product_image"})
for item in product_image:
img1 = item.find("img")
print(img1)
答案 0 :(得分:2)
使用:
soup.find_all("li", class_="product_summary")
或者只是:
soup.find_all(class_="product_summary")
请参阅searching by CSS class的文档。
搜索具有特定CSS类的标记非常有用,但CSS属性的名称“class”是Python中的保留字。使用
按CSS类进行搜索class
作为关键字参数会给出语法错误。从Beautiful Soup 4.1.2开始,您可以使用关键字参数class_
答案 1 :(得分:1)
我认为你可以使用这样的正则表达式:
import re
product_image = soup.find_all("div", {"class": re.compile("^product_image")})