11

次のような構造のスクレイピングを行っているWebサイトがあります。CDataブロックから情報を取得できるようにしたいと思います。

私はBeautifulSoupを使用してページから他の情報を引き出しているので、ソリューションがそれで機能する場合は、Pythonの初心者であるため、学習曲線を抑えるのに役立ちます。具体的には、CDataステートメントに隠されている2つの異なるタイプのデータを取得したいと思います。最初は単なるテキストです。正規表現を投げて必要なものを取得できると確信しています。2番目のタイプでは、html要素を含むデータを独自のbeautifulsoupにドロップできれば、それを解析できます。

私はPythonとbeautifulsoupを学んでいるだけなので、CDataだけを提供する魔法の呪文を見つけるのに苦労しています。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<title>
   Cows and Sheep
  </title>
</head>
<body>
 <div id="main">
  <div id="main-precontents">
   <div id="main-contents" class="main-contents">
    <script type="text/javascript">
       //<![CDATA[var _ = g_cow;_[7654]={cowname_enus:'cows rule!',leather_quality:99,icon:'cow_level_23'};_[37357]={sheepname_enus:'baa breath',wool_quality:75,icon:'sheep_level_23'};_[39654].cowmeat_enus = '<table><tr><td><b class="q4">cows rule!</b><br></br>
       <!--ts-->
       get it now<table width="100%"><tr><td>NOW</td><th>NOW</th></tr></table><span>244 Cows</span><br></br>67 leather<br></br>68 Brains
       <!--yy-->
       <span class="q0">Cow Bonus: +9 Cow Power</span><br></br>Sheep Power 60 / 60<br></br>Sheep 88<br></br>Cow Level 555</td></tr></table>
       <!--?5695:5:40:45-->
       ';
        //]]>
      </script>
     </div>
     </div>
    </div>
 </body>
</html>
4

5 に答える 5

14

CData を取得する BeautifulSoupで注意する必要があることの 1 つは、lxml パーサーを使用しないことです。

デフォルトでは、lxml パーサーはツリーから CDATA セクションを削除し、プレーン テキスト コンテンツに置き換えます。詳細はこちら

#Trying it with html.parser


>>> from bs4 import BeautifulSoup
>>> import bs4
>>> s='''<?xml version="1.0" ?>
<foo>
    <bar><![CDATA[
        aaaaaaaaaaaaa
    ]]></bar>
</foo>'''
>>> soup = BeautifulSoup(s, "html.parser")
>>> soup.find(text=lambda tag: isinstance(tag, bs4.CData)).string.strip()
'aaaaaaaaaaaaa'
>>> 
于 2016-12-28T14:58:03.290 に答える
13

BeautifulSoup は、CData を「ナビゲート可能な文字列」の特別なケース (サブクラス) と見なします。たとえば、次のようになります。

import BeautifulSoup

txt = '''<foobar>We have
       <![CDATA[some data here]]>
       and more.
       </foobar>'''

soup = BeautifulSoup.BeautifulSoup(txt)
for cd in soup.findAll(text=True):
  if isinstance(cd, BeautifulSoup.CData):
    print 'CData contents: %r' % cd

あなたの場合はもちろん、ドキュメント ツリー全体ではなく、「main-contents」ID を持つ div から始まるサブツリーを調べることができます。

于 2010-01-09T03:31:41.673 に答える
4

これを試すことができます:

from BeautifulSoup import BeautifulSoup

// source.html contains your html above
f = open('source.html')
soup = BeautifulSoup(''.join(f.readlines()))
s = soup.findAll('script')
cdata = s[0].contents[0]

これにより、cdata の内容が得られるはずです。

アップデート

これは少しきれいかもしれません:

from BeautifulSoup import BeautifulSoup
import re

// source.html contains your html above
f = open('source.html')
soup = BeautifulSoup(''.join(f.readlines()))
cdata = soup.find(text=re.compile("CDATA"))

個人的な好みですが、下の方が好きです。

于 2010-01-09T03:19:21.430 に答える
0
import re
from bs4 import BeautifulSoup

soup = BeautifulSoup(content)
for x in soup.find_all('item'):
    print re.sub('[\[CDATA\]]', '', x.string)
于 2014-05-20T08:16:52.743 に答える