python爬虫類はseleniumを利用して自動でページをめくってある魚のデータの構想を取ることを実現します。
基本的な考え方:
まず開発者ツールでデータを抽出するラベル列を見つけます。

xpath位置決めを利用してデータを抽出する必要があるリスト

その後、対応するデータを1つずつ抽出します。

csvにデータを保存:

開発者ツールを使って次のページのボタンのあるラベルを見つけます。

このラベルオブジェクトをxpathで抽出して返します。

イベントを呼び出し、上記のプロセスを繰り返します。

最終効果図:

コード:
まず開発者ツールでデータを抽出するラベル列を見つけます。

xpath位置決めを利用してデータを抽出する必要があるリスト

その後、対応するデータを1つずつ抽出します。

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'
','',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, ,
")
self.start_csv = False
# csv
f.write(str)
f.write('
')
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()
ここで、python爬虫類についてはseleniumを利用して自動的にページをめくってある魚のデータを取る構想について詳しく解説した文章を紹介します。これに関連して、python爬虫類は自動的にページをめくってある魚のデータの内容を取ることができます。私達の以前の文章を検索してください。または引き続き下記の関連文章をご覧ください。これからもよろしくお願いします。