如何提取所有包含特定元素(不是 class、span、a 或 li)的 div?

Sky*_*erX 0 html css python beautifulsoup web-scraping

我正在尝试从包含以下许多 div 的网页中提取内容(显然所有数据都具有不同的数据,除了初始部分):

<div data-asin="B007R2E578" data-index="0" 
  class="sg-col-20-of-24 s-result-item sg-col-0-of-12 sg-col-28-of-32 sg-col-16-of-20 AdHolder sg-col sg-col-32-of-36 sg-col-12-of-16 sg-col-24-of-28">
  <div class="sg-col-inner">
Run Code Online (Sandbox Code Playgroud)

所有这些 div 的开头都相同:<div data-asin=

我正在尝试使用 Beautifulsoup 中的 find_all 函数提取所有这些:

structure = soup.find_all('div','data-asin=')
Run Code Online (Sandbox Code Playgroud)

但是它总是返回一个空列表。

我不想使用正则表达式。

BeautifulSoup中是否有任何函数可以获取所有这些div?

And*_*ely 5

您可以使用 CSS 选择器div[data-asin](选择所有存在属性的位置)<div>data-asin

data = '''<div data-asin="B007R2E578" data-index="0"
  class="sg-col-20-of-24 s-result-item sg-col-0-of-12 sg-col-28-of-32 sg-col-16-of-20 AdHolder sg-col sg-col-32-of-36 sg-col-12-of-16 sg-col-24-of-28">
  <div class="sg-col-inner">
   SOME DATA
  </div>
</div>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'lxml')

for div in soup.select('div[data-asin]'):
    print(div['data-asin'], div.get_text(strip=True))
Run Code Online (Sandbox Code Playgroud)

印刷:

B007R2E578 SOME DATA
Run Code Online (Sandbox Code Playgroud)

进一步阅读:

CSS 选择器参考

编辑:要从亚马逊获取一些数据:

from bs4 import BeautifulSoup
import requests

url = 'https://www.amazon.com/s?k=iron&ref=nb_sb_noss_2'
headers = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0'}

soup = BeautifulSoup(requests.get(url, headers=headers).text, 'lxml')

for div in soup.select('div[data-asin]'):
    print(div['data-asin'])
    if div.select_one('.a-price'):
        print(div.select_one('.a-price ').get_text('|',strip=True).split('|')[0])
    if div.select_one('.a-text-normal'):
        print(div.select_one('.a-text-normal').text)
Run Code Online (Sandbox Code Playgroud)

印刷:

B004ILTH1K
$62.81

Rowenta DW5080 1700-Watt Micro Steam Iron Stainless Steel Soleplate with Auto-Off, 400-Hole, Brown

B00OL5P1G8
$21.99

Sunbeam Steam Master 1400 Watt Mid-size Anti-Drip Non-Stick Soleplate Iron with Variable Steam control and 8' Retractable Cord, Black/Blue, GCSBCL-202-000

...etc.
Run Code Online (Sandbox Code Playgroud)