LoginSignup
0
0

More than 1 year has passed since last update.

Python の BeautifulSoup.find() の戻り値を確認

Last updated at Posted at 2022-04-01

BeautifulSoup.find() の戻り値を簡単に確認してみた。

$ python
Python 3.10.3 (main, Mar 29 2022, 01:35:20) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from bs4 import BeautifulSoup
>>> inner_html = r'''
...     <body>
...     <div class="summarycount">524</div>
...     <div class="foo">
...     <a href="https://www.example.com/">go to exmaple.com</a>
...     </div>
...     </body>
... '''
>>> soup = BeautifulSoup(inner_html)
>>> score = soup.find('div', attrs={'class' : 'summarycount'})
>>> print(type(score))
<class'bs4.element.Tag'>
>>> print(score.contents)
['524']
>>> score = soup.find('div').get('class')
>>> print(type(score))
<class'list'>
>>> print(score)
['summarycount']
>>> print(score[0])
summarycount
>>> score = soup.find('div', attrs={'class' : 'foo'})
>>> print(type(score))
<class'bs4.element.Tag'>
>>> print(score.contents)
['\n', <a href="https://www.example.com/">go to exmaple.com</a>, '\n']
>>> score = soup.find('a').get('href')
>>> print(type(score))
<class'str'>
>>> print(score)
https://www.example.com/
>>> score = soup.find('a').get('target')
>>> print(type(score))
<class'NoneType'>
>>> print(score)
None
>>> score = soup.find('span')
>>> print(type(score))
<class'NoneType'>
>>> print(score)
None
>>> exit()
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0