2016-10-09 34 views
0

我們可以使用BeautifulSoup中的get_text()函數獲取標籤內的文本。但是,如果文本區域包含一些類似html的代碼,該怎麼辦使用beautifulsoup打印html內容形成文本區域

例子:

from bs4 import BeautifulSoup 
html = "<html><h1>#include <stdio.h></h1></html>" 
soup = BeautifulSoup(html,"lxml") 
print soup.h1.get_text() 

上述程序打印 「的#include」 但我想這是裏面H1全文。 這只是一個小例子。我正在從網上抓取C++代碼。我已經導航到代碼存在的文本區域,但是當我打印它時,它不會打印頭文件。 多行文本:

<textarea rows="20" cols="70" name="file" id="file" style="width: 100%;" data-input-file="1">#include <bits/stdc++.h> 
using namespace std; 
struct points 
{ 
    int x; 
    int count; 
}; 
points a[105]; 
int main() 
{ 
    int n; 
    int k; 
    int t; 
    int i; 
    int j; 

    scanf("%d",&t); 

    while(t--) { 
     scanf("%d%d",&n,&k); 
     for(i = 1; i <= k; i++) { 
      scanf("%d",&a[i].x); 
      a[i].count = 1; 
      if(a[i].x == -1) { 
       a[i].x = 1000000000; 
      } 
     } 

     for(i = 2; i <= k; i++) { 
      for(j = 1; j < i; j++) { 
       if((a[i-j].x + a[j].x) < a[i].x && (a[i-j].count + a[j].count) <= n) { 
        a[i].x = a[i-j].x + a[j].x; 
        a[i].count = a[i-j].count + a[j].count; 
       } 
      } 
     } 

     if(a[k].x == 1000000000) { 
      printf("-1\n"); 
     } 
     else { 
      printf("%d\n",a[k].x); 
     } 
    } 



} 
</textarea> 

我刮代碼:

from robobrowser import RoboBrowser 
browser = RoboBrowser(parser = "lxml") 
browser.open('http://www.spoj.com/') 
form = browser.get_form(id='login-form') 
form['login_user'].value = username 
form['password'].value = password 
browser.submit_form(form) 
browser.open('http://www.spoj.com/myaccount') 
l = browser.find(id = "user-profile-tables").find_all('td') 
link = l[0].a['href'] 
link = "http://www.spoj.com" + link 
browser.open(link) 
codelink = browser.find(title = 'Edit source code')['href'] 
codelang = browser.find(class_ = 'slang text-center').get_text() 
codelink = "http://www.spoj.com" + codelink 
browser.open(codelink) 
print browser.find(id = 'submit_form').textarea.get_text() 

有什麼辦法實現呢?

回答

1

的問題是LT和GT標誌應像下面進行轉義:

from bs4 import BeautifulSoup 
html = "<html><h1>#include &lt;stdio.h&gt;</h1></html>" 
soup = BeautifulSoup(html,"lxml") 
print(soup.h1.get_text()) 

然後會給你:

#include <stdio.h> 

無解析器的要考慮到文本,除非他們被逃脫。每個人都會給你#include <stdio.h></stdio.h>

你可能只需求助於正則表達式來從源自身中提取包含語句。

patt = re.compile(r"<h1>(\s+)?(#include\s+.*?)(\s+)?</h1>") 
+0

我從網上抓取一個C代碼,我得到的是一個沒有頭文件的代碼。我不認爲我可以用它完成你的想法,因爲我手頭沒有代碼。 –

+0

@ShivamMitra,你能分享一個樣本網址嗎?如果它顯示在瀏覽器中,那麼它應該被轉義或者你會看到的是#include –

+0

我編輯過這個帖子。 –