簡體   English   中英

如何在“br”之前提取文本?

[英]How to extract text before “br”?

我有一個小問題。 我使用的是python 2.7.8。 我試圖提取這應該是前<BR>文本。 我喜歡:

<html>
<body>
<div class="entry-content" >
<p>Here is a listing of C interview questions on “Variable Names” along with answers, explanations and/or solutions:
</p>

<p>1. C99 standard guarantees uniqueness of ____ characters for internal names.<br>
a) 31<br>
b) 63<br>
c) 12<br>
d) 14</p>
<p> more </p>
<p>2. C99 standard guarantess uniqueness of _____ characters for external names.<br>
a) 31<br>
b) 6<br>
c) 12<br>
d) 14</p>
 </div>
</body>
</html>

我試過的代碼目前正在br之前,而不是在br之前。這是代碼:

from BeautifulSoup import BeautifulSoup, NavigableString, Tag
soup2 = BeautifulSoup(htmls)

for br2 in soup2.findAll('br'):
    next = br2.previousSibling
    if not (next and isinstance(next,NavigableString)):
        continue
    next2 = next.previousSibling
    if next2 and isinstance(next2,Tag) and next2.name == 'br':
        text = str(next).strip()
        if text:

            print "Found:", next.encode('utf-8')

輸出給了我:

Found: 
a) 31
Found: 
b) 63
Found: 
c) 12
Found:
d) 14 
a) 31
Found: 
b) 6
Found: 
c) 12
Found:
d) 14 
Found:

知道我哪里做錯了。

首先,我將切換到BeautifulSoup版本4 BeautifulSoup3很老了,不再維護了:

美麗的湯3已被美麗的湯4取代。

Beautiful Soup 3僅適用於Python 2.x,但Beautiful Soup 4也適用於Python 3.x. Beautiful Soup 4速度更快,功能更多,可與第三方解析器(如lxml和html5lib)配合使用。 測試期結束后,您應該為所有新項目使用Beautiful Soup 4。

跑:

pip install beautifulsoup4

並從以下位置更改您的import語句:

from BeautifulSoup import BeautifulSoup

至:

from bs4 import BeautifulSoup

現在,我想在這里做的是找到問題文本,並得到如下br兄弟姐妹 對於每個兄弟,獲取next_sibling ,這將是答案選項。 工作代碼:

soup = BeautifulSoup(data, "html5lib")  # using "html5lib" parser here

for question in soup.find_all(text=re.compile(r"^\d+\.")):
    answers = [br.next_sibling.strip() for br in question.find_next_siblings("br")]

    print(question)
    print(answers)
    print("------")

對於問題中提供的示例HTML,它會打印:

1. C99 standard guarantees uniqueness of ____ characters for internal names.
[u'a) 31', u'b) 63', u'c) 12', u'd) 14']
------
2. C99 standard guarantess uniqueness of _____ characters for external names.
[u'a) 31', u'b) 6', u'c) 12', u'd) 14']
------

請注意,您可能需要安裝html5lib

pip install html5lib

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM