Skip to main content
 首页 » 编程设计

python之BeautifulSoup 中的自定义属性

2025年05月04日20落叶无声

我正在尝试使用 Beautiful soup 来定位具有非标准属性的 DIV。这是 DIV:

`<div data-asin="099655596X" data-index="1" class="sg-col-20-of-24 s-result-item sg-col-0-of-12 sg-col-28-of-32 sg-col-16-of-20 sg-col sg-col-32-of-36 sg-col-12-of-16 sg-col-24-of-28" data-cel widget="search_result_1">` 

我需要找到具有 data-asin 属性的 find_all DIV,并获取 asin。 BS 似乎支持此功能,但我所做的不起作用。这是我的代码不起作用:

`rows = soup.find_all(attrs={"data-asin": "value"})` 

我需要如何在 Python3.7 中制作我的 BS 才能找到所有这些 DIV?

请您参考如下方法:

使用 Css Selector 来获取它。

from bs4 import BeautifulSoup 
html = ''' 
<div data-asin="099655596X" data-index="1" class="sg-col-20-of-24 s-result-item sg-col-0-of-12 sg-col-28-of-32 sg-col-16-of-20 sg-col sg-col-32-of-36 sg-col-12-of-16 sg-col-24-of-28" data-cel widget="search_result_1"> 
''' 
soup = BeautifulSoup(html,'html.parser') 
items=soup.select('div[data-asin="099655596X"]') 
for item in items: 
    print(item['data-asin']) 

输出:

099655596X 

或

from bs4 import BeautifulSoup 
html = ''' 
<div data-asin="099655596X" data-index="1" class="sg-col-20-of-24 s-result-item sg-col-0-of-12 sg-col-28-of-32 sg-col-16-of-20 sg-col sg-col-32-of-36 sg-col-12-of-16 sg-col-24-of-28" data-cel widget="search_result_1"> 
''' 
soup = BeautifulSoup(html,'html.parser') 
items=soup.select('div[data-asin$="X"]') 
for item in items: 
    print(item['data-asin'])