Пользовательские атрибуты в BeautifulSoup? - PullRequest
1 голос
/ 04 апреля 2019

Я пытаюсь использовать 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">`

Мне нужно найти DIV_all DIV с атрибутом data-asin, а также получить asin. BS, кажется, поддерживает эту функцию, но то, что я делаю, не работает. Вот мой код, который не работает:

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

Как мне создать свой BS в Python3.7, чтобы найти все эти DIV?

1 Ответ

4 голосов
/ 04 апреля 2019

Используйте 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'])

OutPut:

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'])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...