2
4

2 回答 2

2

text=True从您的代码中删除它应该可以正常工作:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''
... <html>
... <body>
... <a href = "http:\\www.google.com">Google<br>
... <a href = "http:\\www.example.com">Example</a>
... </body>
... </html>
... ''')
>>> [a.get_text().strip() for a in soup.find_all('a')]
[u'Google', u'Example']
>>> [a.get_text().strip() for a in soup.find_all('a', text=True)]
[u'Example']
于 2012-12-19T04:48:03.780 回答
0

试试这个代码:

from BeautifulSoup import BeautifulSoup

text = '''
<html>
<body>
<a href = "http:\\www.google.com">Google<br>
<a href = "http:\\www.example.com">Example</a>
</body>
</html>
'''

soup = BeautifulSoup(text)

for link in soup.findAll('a'):
    if link.string != None:
        print link.string

这是我运行代码时的输出:

例子

只需替换texttext = open('sol.html').read(),或者您需要去那里的任何内容。

于 2012-12-19T04:35:37.630 回答