解析使用BeautifulSoup

问题描述:

一个html文件,我有这个HTML文件:解析使用BeautifulSoup

<html> 
    <head></head> 
    <body> 
     Text1 
     Text2 
     <a href="XYCL7Q.html"> 
      Text3 
     </a> 
    </body> 
</html> 

我想收集分别文本1,文本2和文本3。对于Text3我没有问题,但我无法捕获Text1-2;通过这样做:

from urllib import urlopen 
from bs4 import BeautifulSoup 

url = 'myUrl'; 
html = urlopen(url).read() 
soup = BeautifulSoup(html) 
soup.body.get_text() 

我得到的所有文本(第一个问题,因为我得到的文本3再次)没有得到很好的分离,因为Text1-2可能包含一些空间......举例来说,如果文本1是“世界你好”和Text2“foo bar”,最后我想列出2个字符串:

results = ['hello world', 'foo bar'] 

我该怎么做?谢谢你的回答...

你想要的文本是“body”的第一个子节点。你可以把它拉出来并剥离污迹

>>> from bs4 import BeautifulSoup as bs 
>>> soup=bs("""<html> 
...  <head></head> 
...  <body> 
...   Text1 
...   Text2 
...   <a href="XYCL7Q.html"> 
...    Text3 
...   </a> 
...  </body> 
... </html>""") 
... 
>>> body=soup.find('body') 
>>> type(next(body.children)) 
<class 'bs4.element.NavigableString'> 
>>> next(body.children) 
u'\n  Text1 \n  Text2\n  ' 
>>> [stripped for stripped in (item.strip() for item in next(body.children).split('\n')) if stripped] 
[u'Text1', u'Text2']