kry*_*rro 1 python beautifulsoup
我正在尝试使用Beautiful汤来定位具有非标准属性的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">`
Run Code Online (Sandbox Code Playgroud)
我需要使用data-asin属性找到find_all DIV,并同时获取asin。BS似乎支持此功能,但是我正在做的事没有用。这是我的代码不起作用:
`rows = soup.find_all(attrs={"data-asin": "value"})`
Run Code Online (Sandbox Code Playgroud)
我如何在Python3.7中制作BS来查找所有这些DIV?
使用CSS选择器可以做到这一点。
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'])
Run Code Online (Sandbox Code Playgroud)
输出:
099655596X
Run Code Online (Sandbox Code Playgroud)
要么
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'])
Run Code Online (Sandbox Code Playgroud)