本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理,
以上文章來源于CSND,作者 sweetheart7-7
基本思路:
首先用開發者工具找到需要提取資料的標簽串列:
利用xpath定位需要提取資料的串列
然后再逐個提取相應的資料:
保存資料到csv:
利用開發者工具找到下一頁按鈕所在標簽:
利用xpath提取此標簽物件并回傳:
呼叫點擊事件,并回圈上述程序:
最終效果圖:
代碼:
from selenium import webdriver
import time
import re
class Douyu(object):
def __init__(self):
# 開始時的url
self.start_url = "https://www.douyu.com/directory/all"
# 實體化一個Chrome物件
self.driver = webdriver.Chrome()
# 用來寫csv檔案的標題
self.start_csv = True
def __del__(self):
self.driver.quit()
def get_content(self):
# 先讓程式兩秒,保證頁面所有內容都可以加載出來
time.sleep(2)
item = {}
# 獲取進入下一頁的標簽
next_page = self.driver.find_element_by_xpath("//span[text()='下一頁']/..")
# 獲取用于判斷是否是最后一頁的屬性
is_next_url = next_page.get_attribute("aria-disabled")
# 獲取存盤資訊的所有li標簽的串列
li_list = self.driver.find_elements_by_xpath("//ul[@class='layout-Cover-list']//li")
# 提取需要的資料
for li in li_list:
item["user-id"] = li.find_element_by_xpath(".//div[@class='DyListCover-userName']").text
item["img"] = li.find_element_by_xpath(".//div[@class='DyListCover-imgWrap']//img").get_attribute("src")
item['class-name'] = li.find_element_by_xpath(".//span[@class='DyListCover-zone']").text
item["click-hot"] = li.find_element_by_xpath(".//span[@class='DyListCover-hot']").text
item["click-hot"] = re.sub(r'\n','',item['click-hot'])
# 保存資料
self.save_csv(item)
# 回傳是否有下一頁和下一頁的點擊事件的標簽,
return next_page,is_next_url
def save_csv(self,item):
# 將提取存放到csv檔案中的內容連接為csv格式檔案
str = ','.join([i for i in item.values()])
with open('./douyu.csv','a',encoding='utf-8') as f:
if self.start_csv:
f.write("用戶id,image,所屬類,點擊熱度\n")
self.start_csv = False
# 將字串寫入csv檔案
f.write(str)
f.write('\n')
print("save success")
def run(self):
# 啟動chrome并定位到相應頁面
self.driver.get(self.start_url)
while True:
# 開始提取資料,并獲取下一頁的元素
next_page,is_next = self.get_content()
if is_next!='false':
break
# 點擊下一頁
next_page.click()
if __name__=='__main__':
douyu_spider = Douyu()
douyu_spider.run()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/163399.html
標籤:Python
下一篇:python基礎知識1
