1. 程式人生 > >爬蟲實戰-xvideos視訊爬蟲

爬蟲實戰-xvideos視訊爬蟲

前情概要

舍友說他的VPN要到期了,讓我物盡其用,所以幫他爬點小電影回來,我想了想正好是對我爬蟲能力的一次測驗,雖然我不看,但是我還是嘗試製作了一個X站的爬蟲。

我是用的是Anaconda下自帶的Spyder IDE,python3.7 。

首先

我考慮的是爬蟲的擴散,但是不論用是BeautifulSoup還是json解析都找不到正確的地址,於是我使用了selenium模擬真人操作,

設一個全域性變數pages來儲存地址資訊。

pages=set()
def getUrls(start_url):
    browser = webdriver.Chrome()
    browser.get(start_url)
    # 通過css選擇器查詢
    urls = browser.find_elements_by_css_selector('.thumb a')
    
    global pages
    
    for x in urls:
        url = x.get_attribute('href')
        if url not in pages:
    #        新頁面
            print(url)
            pages.add(url)
        else:
            print("已經下載過")
    time.sleep(5)
    browser.quit()
    

其次

要從每個頁面中提取出可以下載視訊的url

要注意的是如果如果不加     content = urllib.request.urlopen(req).read() 會出現報錯

can't use a string pattern on a bytes-like object 

通過解析Html頁面發現在Script標籤裡存在我們需要的資料,用正則表示式提取

def download_the_av(url):
    req = urllib.request.Request(url)
    content = urllib.request.urlopen(req).read()
#       注意 不加這行會出現錯誤
    content = content.decode('utf-8')
#    小於一百預設失敗
    while len(content)<100:
        print("try again...")
        content = urllib.request.urlopen(req).read()
        content = content.decode('utf-8')
    print( "All length:%s" %(str(len(content))))
    titleRe = "setVideoTitle\(\'(.+?)\'\);"
    lowUrlRe = "setVideoUrlLow\(\'(.+?)\'\);"
    patternTitle = re.compile(titleRe)

    patternLowUrl = re.compile(lowUrlRe)
    to_find = content
    
    matchTitle = patternTitle.search(to_find)
    matchLowUrl = patternLowUrl.search(to_find)
    if matchTitle:
        title = matchTitle.group(1)+".mp4"
        print (title)

    if matchLowUrl:
        lowUrl = matchLowUrl.group(1)
        print (lowUrl)
    if len(lowUrl)>0:
        save_file(lowUrl,title)

最後

將得到的視訊url下載到本地,並給上得到的title,就好了

要注意的是每個變數的type 不能亂賦值,很容易報錯的

程式碼

儲存在我的git庫中,有需要的話,大家可以實驗一下,下載的視訊請勿用作商業用途

https://github.com/Kratosssss/xvideos_spyder