鍍金池/ 問答/Python  數(shù)據(jù)庫/ 我這個如何處理網(wǎng)站的xml structure文件

我這個如何處理網(wǎng)站的xml structure文件

我想輸入某個B站番號,然后爬取其中視頻的彈幕,我采用的方法來源于知乎

b站的視頻有兩個相關(guān)的id number,一個是cid,一個是我們都知道的AV number。抓取彈幕需要的是cid。最簡單的方法是直接查看網(wǎng)頁源代碼搜索cid,這樣就可以得到單獨(dú)一個視頻的cid了。然后通過這個網(wǎng)址就可以得到相關(guān)視頻的彈幕“http://comment.bilibili.com/“ + cid + “.xml“。 不過問題在于,因?yàn)閎站彈幕的設(shè)置問題,每個視頻是有一個彈幕上限的。 如果數(shù)量到達(dá)一定數(shù)量,就會被清理。所以這個方法只能得到香瓜能視頻下面現(xiàn)在的彈幕。 當(dāng)然如果批量處理的話,需要用正則去搜索這個cid,然后通過這個url去處理一下xml structure的文件。

作者:劉岳
鏈接:https://www.zhihu.com/questio...
來源:知乎
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。

我的代碼如下:

#1表示選擇使用正則
#2表示選擇使用xpath

import requests
import re
from lxml import etree

#抓取網(wǎng)頁
def getHTML(url,op):
    header={"User-Agent":'Mozilla/5.0'}
    try:
        r = requests.get(url,timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        if(op==1):return r.text
        else:return r.content
    except:
        return "抓取失?。?
#獲取cid信息
def paraHTML(html):
    cid = re.findall(r'cid\=(.*)\&aid',html)
    return cid

def print_comment(html):
    comments = etree.HTML(html)
    print(len(comments))

        
def main():
    raw_url = "https://www.bilibili.com/video/"
    av_number = input("請輸入B站AV番號")
    url = raw_url+av_number
    html = getHTML(url,1)
    cid = paraHTML(html)[0]
    print(type(cid))
    comment_url = "http://comment.bilibili.com/cid.xml"
    comment_url = comment_url.replace("cid",cid)
    print(comment_url)
    comment_html = getHTML(comment_url,2)
    print_comment(comment_html)
    
main()

彈幕的那個網(wǎng)站,右擊查看屬性,彈幕內(nèi)容全在一個個p標(biāo)簽里,我一開始用xpath的方法抓取,卻抓取不了,為空,后來我直接打印出其中的長度,發(fā)現(xiàn)為1,并且是一個空列表,這是為什么?

回答
編輯回答
硬扛
def print_comment(html):
    comments = etree.fromstring(html)     # 是xml不是html
    print(len(comments.xpath('/i/d')))
2018年1月26日 09:21