文章目录提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
- 前言
一、Anonymous Github是什么?
二、使用步骤
前言
通常在提交学术论文的时候也需要提交实验材料和源码,这时候,我们通常重新申请一个github账号,然后新建一个仓库(repo)来安放我们的数据。
现在,有了另外一个方案(Anonymous Github),即匿名化自己的仓库(甚至是私人仓库)。
这样就不用每次都重新注册账号啦。
但是Anonymous Github不支持克隆匿名后的仓库,需要一个文件一个文件的下载,本文介绍一种通过Selenium爬取仓库的方法。
一、Anonymous Github是什么?
大家可以参考一下另一位博主的文章:Anonymous Github.
二、使用步骤
建议使用jupyter notebook分段使用下述代码,出现问题可以及时调整:
from selenium import webdriver
from selenium.webdriver.common.by import By
import urllib.request
import os
options = webdriver.ChromeOptions()
prefs = {'download.default_directory': 'E:\crawler', #存储位置
"download.prompt_for_download": False,
'profile.default_content_settings.popups': 0, # 设置为0,禁止d出窗口
}
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(options=options)
link = "https://anonymous.4open.science/r/****/" # 根据自己要爬取的仓库进行修改
driver.get(link)
mulus = [] # 用来存储每个目录元素的ng-class属性
# 由于该网站为动态加载,所以需要依次打开目录中的每个文件夹,以获取每个文件夹及每个文件的属性
# 打开第一层
dirs = driver.find_elements(By.XPATH,'//li[@]')
for dir in dirs:
mulus.append(dir.get_attribute('ng-class'))
dir.click()
# 打开第二层
dirs1 = driver.find_elements(By.XPATH,'//li[@]')
for dir1 in dirs1:
mulus.append(dir1.get_attribute('ng-class'))
# 避免之前打开的文件夹被关上
if dir1 not in dirs:
dir1.click()
# 打开第三层
dirs2 = driver.find_elements(By.XPATH,'//li[@]')
for dir2 in dirs2:
mulus.append(dir2.get_attribute('ng-class'))
# 避免之前打开的文件夹被关上
if dir2 not in dirs1:
dir2.click()
# 打开第四层
dirs3 = driver.find_elements(By.XPATH,'//li[@]')
for dir3 in dirs3:
mulus.append(dir3.get_attribute('ng-class'))
# 避免之前打开的文件夹被关上
if dir3 not in dirs2:
dir3.click()
# 获取每个文件元素
files = driver.find_elements(By.XPATH,'//li[@]')
# 截取mulus的目录字段,并将'/'换为'\'
win_mulus = []
for mulu in mulus:
win_mulus.append(mulu[19:mulu.find("'),")].replace('/','\'))
# 根据获取到的目录在电脑上创建文件夹
path = "E:\\crawler\"
for win_mulu in win_mulus:
new_path = path + win_mulu
os.makedirs(new_path)
# 获取每个文件的ng-class属性
wenjians = []
for file in files:
wenjians.append(file.get_attribute('ng-class'))
file_paths = []
# 截取wenjians的目录字段,并将'/'换为'\'
for wenjian in wenjians:
file_paths.append(wenjian[19:wenjian.find("'),")].replace('/','\'))
# 下载文件到指定文件夹的函数
def get_file_by_url(file_path, url):
print("Try downloading file: {}".format(url))
filename = url.split('/')[-1]
if os.path.exists(file_path):
print("File have already exist. skip")
else:
try:
urllib.request.urlretrieve(url, filename=file_path)
except Exception as e:
print("Error occurred when downloading file, error message:")
print(e)
# 防止网站反爬
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36')]
urllib.request.install_opener(opener)
path = "E:\\crawler\"
# 下载仓库中的每个文件
for file_path in file_paths[10655:]:
new_path = path + file_path
url = "https://anonymous.4open.science/api/repo/****/file" + file_path.replace('\','/') # 根据自己要爬取的仓库进行修改
get_file_by_url(new_path,url)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)