python如何解析htm

2024-09-25 00:31:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用BeautifulSoup解析python中的htmldiv。在

我的代码:

url = "http://german-bash.org/action/random"
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
for div in soup.findAll('div','zitat'):
    output = div.find('span', 'quote_zeile').string
    print(output)

我要把所有的斯潘都放在沙发上”zitat区“但这不管用


Tags: 代码orgdivbashhttpurloutputresponse
1条回答
网友
1楼 · 发布于 2024-09-25 00:31:19

您只获取第一个这样的<span>。再次使用.findAll()查找所有此类跨度:

html = response.read()
soup = BeautifulSoup(html, from_encoding=response.info().getparam('charset'))
for div in soup.findAll('div','zitat'):
    for span in div.findAll('span', 'quote_zeile'):
        print span.string

这会产生:

^{pr2}$

请注意,我还告诉BeautifulSoup要使用什么编码,取自响应Content-Type报头;这对这个页面很重要,因为没有它,beauthoulsoup就猜错了。在

相关问题 更多 >