我正在尝试从一个包含以下许多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">
所有这些div均以<div data-asin=
我正在尝试使用Beautifulsoup的find_all函数提取所有这些对象:
structure = soup.find_all('div','data-asin=')
但是它总是返回一个空列表。
我不想使用正则表达式。
BeautifulSoup中是否有任何可以获取所有div的函数?
答案 0 :(得分:3)
您可以使用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))
打印:
B007R2E578 SOME DATA
进一步阅读:
编辑:要从Amazon获取一些数据:
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)
打印:
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.
答案 1 :(得分:1)
查找所有div标签,然后进行列表理解,如果该属性具有该属性,则将该属性值放入列表:
html = '''<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">'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
divs = soup.find_all('div')
a_list = [ div['data-asin'] for div in divs if div.has_attr('data-asin')]
答案 2 :(得分:0)
这使您所有的div然后进行过滤
$(':div')。each(function(){
Var ele = $(this);
});