LoginSignup
0
1

More than 3 years have passed since last update.

Beautiful Soupで数字始まりのidをselectする

Posted at

急いでいる人用

  • BeautifulSoup 4.7.0 以降 で以下の処置が必要です。
  • cssエスケープで記述します。
  • 先頭の1\\31 にエスケープすると記述できます。
  • 0〜9までの数字は \\30 〜 \\39 のようにエスケープします。
  • 1234の場合は \\31 234 として、先頭の1桁をエスケープしてスペースを入れます。
from bs4 import BeautifulSoup
html = '<h1 id="1">test</h1>'
soup = BeautifulSoup(html,'lxml')
soup.select('#\\31')
# >>> [<h1 id="1">test</h1>]
from bs4 import BeautifulSoup
html = '<h1 id="0123">test</h1>'
soup = BeautifulSoup(html,'lxml')
soup.select('#\\30 123')
# >>> [<h1 id="0123">test</h1>]

BeautifulSoup 4.6.xでの動作

  • cssエスケープなしでヒットします。
  • cssエスケープをするとヒットしません。
from bs4 import BeautifulSoup
html = '<h1 id="1234">test</h1>'
soup = BeautifulSoup(html,'lxml')
soup.select('h1#1234')
# >>> [<h1 id="1234">test</h1>]

BeautifulSoup 4.7.0以降の変更

BeautifulSoup 4.7.0からcss slector のparserの実装がBeautifulSoup独自からsoupsieveに変更になりました。
これにより、複雑なcssセレクタや最新のcssセレクタに対応できるようになっているようです。
https://github.com/facelessuser/soupsieve

cssエスケープ

こちらの記事が大変参考になりました。
https://qiita.com/ka-ko/items/feacb4d3ff22666d51b1

cssエスケープを行うツールも紹介されています。
https://mothereff.in/css-escapes

0
1
0

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
1