0

ソースは次のとおりです。

<span class="new"> <a class="blog" href="http://whatever1.com" rel="nofollow">whatever1</a> do something at <a class="others" href="http://example1.com" rel="nofollow">example1</a></span>

<span class="new"> <a class="blog" href="http://whatever2.com" rel="nofollow">whatever2</a> do other things at <a class="others" href="http://example2.com" rel="nofollow">example2</a></span>

<span class="new"> <a class="blog" href="http://whatever3.com" rel="nofollow">whatever3</a> do something at <a class="others" href="http://example3.com" rel="nofollow">example3</a></span> 

<span class="new">その中のすべてを見つけたいのですがdo something at、これが私のコードです。なぜ機能しないのかわかりません:

soup = bs4.BeautifulSoup(html, "lxml")
all_tags = soup.findAll(name = "span", attrs = {"class": "new"}, text = re.compile('do something.*'))

何も見つかりません。上記のタグをすべて削除するtext = re.compile('.*do something.*')と、正規表現パターンに何か問題があることがわかります。正しい形式は何ですか?

4

3 に答える 3

1

いつでもハイブリッド アプローチを試すことができます。

soup = bs4.BeautifulSoup(html, "lxml")
spans = soup.findAll("span", attrs = {"class": "new"})
regex = re.compile('.*do something at.*')
desired_tags = [span for span in spans if regex.match(span.text)]
于 2012-10-25T01:51:24.070 に答える
0

html ファイルの内容を繰り返し処理し、一致する行を出力します。ここでは、ファイルの内容をリスト l に置き換えました。

>>> l = ['<span class="new"> <a class="blog" href="http://whatever1.com" rel="nofollow">whatever1</a> do something at <a class="others" href="http://example1.com" rel="nofollow">example1</a></span>', 

'<span class="new"> <a class="blog" href="http://whatever2.com" rel="nofollow">whatever2</a> do other things at <a class="others" href="http://example2.com" rel="nofollow">example2</a></span>',

'<span class="new"> <a class="blog" href="http://whatever3.com" rel="nofollow">whatever3</a> do something at <a class="others" href="http://example3.com" rel="nofollow">example3</a></span>' ]
>>> for i in range(len(l)):
    if re.search('<span class="new">.*do something.*', l[i]):
        print l[i]


<span class="new"> <a class="blog" href="http://whatever1.com" rel="nofollow">whatever1</a> do something at <a class="others" href="http://example1.com" rel="nofollow">example1</a></span>
<span class="new"> <a class="blog" href="http://whatever3.com" rel="nofollow">whatever3</a> do something at <a class="others" href="http://example3.com" rel="nofollow">example3</a></span>
>>> 
于 2012-10-25T01:50:17.643 に答える
0

これは、私が通常テキストを検索する方法です。

spans = soup.findAll("span", attrs = {"class": "new"})
for s in spans:
    if "do something" in str(s):
于 2012-10-26T04:34:31.220 に答える