爬取知乎單個網頁問題和回答

nt1979發表於2021-09-09
# -*- coding: utf-8 -*-

import urllib
import urllib.request
from bs4 import BeautifulSoup

url=''
request = urllib.request.Request(url)
response = urllib.request.urlopen(url)
page = response.read().decode('utf-8')
soup = BeautifulSoup(page,'html5lib')
# 問題是什麼
question = soup.find_all('h2')[0]
print(question.find('span').string)

# 贊最多的回答
all_answer = soup.find_all('div',class_='zm-item-answer zm-item-expanded')
goodAnswer = 0
bestAnswer = 0
for answer in all_answer:
    goodAnswer = answer.find('span',class_='count').string
    #if(goodAnswer > bestAnswer):
    #    bestAnswer = goodAnswer
    answerText = answer.find('div',class_='zm-editable-content clearfix')

    print(goodAnswer +' '+ answerText.text[:10].replace('n',''))

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/4822/viewspace-2798422/,如需轉載,請註明出處,否則將追究法律責任。

相關文章