python爬虫源代码_零基础自学爬虫(5)B站有哪些爬虫的视频学习资源-附Python源代码...
生活随笔
收集整理的這篇文章主要介紹了
python爬虫源代码_零基础自学爬虫(5)B站有哪些爬虫的视频学习资源-附Python源代码...
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前幾天看到有人提問:。b站哪個python爬蟲視頻講的較好?謝謝各位能解答一下。?
于是順手寫了一個小爬蟲,把數據爬了下來。 今天有空放一下源代碼。
數據源,是在B站搜索框直接搜索“爬蟲”,并選擇按收藏排序。總結果大概50頁,然后爬取該數據。
第一步:啟動 chromedriver,無頭模式。
from time import sleep from datetime import datetime from selenium import webdriver from selenium.webdriver.chrome.options import Options import pandas as pd import re import json# 啟動 driver(無頭模式) def start_driver():chrome_options = Options()chrome_options.add_argument("--headless")chrome_options.add_argument("--disable-gpu")driver = webdriver.Chrome(options=chrome_options)return driver第二步:爬取一頁搜索結果,封裝為函數。
# 獲取一頁搜索結果 def get_onepage(driver,url,n):driver.get(url)sleep(3)rlts = driver.find_elements_by_class_name("info")info = {}pttn = "(http.*?)?from"for rlt in rlts:t1 = rlt.find_element_by_xpath('./div[1]/a')v[n] = {"title":t1.text,"url":re.findall(pttn,t1.get_attribute("href"))[0]}t2 = rlt.find_element_by_xpath('./div[3]')x = t2.text.split('n')v[n]["watch_num"] = x[0]v[n]["update"] = x[1]v[n]["upper"] = x[2]n += 1return v,n第三步:逐頁讀取所有數據。
driver = start_driver() n = 1 pages = 51 for i in range(1,pages):url = "https://search.bilibili.com/all?keyword=%E7%88%AC%E8%99%AB&from_source=nav_suggest_new&order=stow&duration=0&tids_"+str(i)try:v,n = get_onepage(driver,url,n)except:break第四步:數據結果存儲。
# 數據保存為 json 文件 file = "bilibili_crawler.json" with open(file,"w",encoding="utf-8") as f:json.dump(v,f,indent=4,sort_keys=False, ensure_ascii=False)# 也可保存為表格文件 df = pd.DataFrame(v).T file2 = "bilibili_crawler.csv" df.to_csv(file2)點贊,收藏,關注,分享四連。好人一生平安。
看不懂的,評論留言問我。
想要所有數據,站內私信我。
總結
以上是生活随笔為你收集整理的python爬虫源代码_零基础自学爬虫(5)B站有哪些爬虫的视频学习资源-附Python源代码...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 卵巢早衰并发症有哪些
- 下一篇: python wxpython_pyth