我们可以使用BeautifulSoup中的get_text()函数获取标记内的文本。但是如果文本区域包含一些类似html的代码会怎么样呢。
示例:
from bs4 import BeautifulSoup
html = "<html><h1>#include <stdio.h></h1></html>"
soup = BeautifulSoup(html,"lxml")
print soup.h1.get_text()
以上程序打印&#34; #include&#34;但是我希望它在h1里面是全文。 这只是一个小例子。我正在处理从Web上抓取c ++代码。我已导航到存在代码的文本区域,但是当我打印它时,它不会打印头文件。 textarea的:
<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()
有没有办法实现它?
答案 0 :(得分:1)
问题是lt和gt标志应该如下所示进行转义:
from bs4 import BeautifulSoup
html = "<html><h1>#include <stdio.h></h1></html>"
soup = BeautifulSoup(html,"lxml")
print(soup.h1.get_text())
然后会给你:
#include <stdio.h>
除非转义,否则解析器都不会考虑该文本。每个人都会给你#include <stdio.h></stdio.h>
您可能只需要使用正则表达式从源本身中提取include语句。
patt = re.compile(r"<h1>(\s+)?(#include\s+.*?)(\s+)?</h1>")