# 文章标题
title = driver.find_element(By.XPATH, '//div[contains(@class,"article-bar")]//input[contains(@placeholder,"请输入文章标题")]')
title.clear()
if 'title' in front_matter['title'] and front_matter['title']:
title.send_keys(front_matter['title'])
else:
title.send_keys(common_config['title'])
time.sleep(2) # 等待3秒
# 文章标签
if 'tags' in front_matter and front_matter['tags']:
tags = front_matter['tags']
else:
tags = csdn_config['tags']
if tags:
add_tag = driver.find_element(By.XPATH,
'//div[@class="mark_selection"]//button[@class="tag__btn-tag" and contains(text(),"添加文章标签")]')
add_tag.click()
time.sleep(1)
tag_input = driver.find_element(By.XPATH, '//div[@class="mark_selection_box"]//input[contains(@placeholder,"请输入文字搜索")]')
for tag in tags:
tag_input.send_keys(tag)
time.sleep(2)
tag_input.send_keys(Keys.ENTER)
time.sleep(1)
# 关闭按钮
close_button = driver.find_element(By.XPATH, '//div[@class="mark_selection_box"]//button[@title="关闭"]')
close_button.click()
time.sleep(1)
添加封面
CSDN的封面会自动检测文章内容中的图片,把这些图片设置为文章的封面。
当然我们也可以自行设置。
if 'image' in front_matter and front_matter['image']:
file_input = driver.find_element(By.XPATH, "//input[@type='file']")
# 文件上传不支持远程文件上传,所以需要把图片下载到本地
file_input.send_keys(download_image(front_matter['image']))
time.sleep(2)
要注意的是,这里的image地址是在markdown文件中的yaml front matter中设置的。
如图所示:
image-20240507154807745
设置摘要
csdn的摘要部分也没有ID,还是需要通过xpath来进行获取。
这里通过textarea的placeholder来进行获取。
# 摘要
if 'description' in front_matter['description'] and front_matter['description']:
summary = front_matter['description']
else:
summary = common_config['summary']
if summary:
summary_input = driver.find_element(By.XPATH, '//div[@class="desc-box"]//textarea[contains(@placeholder,"摘要:会在推荐、列表等场景外露")]')
summary_input.send_keys(summary)
time.sleep(2)
分类专栏
csdn的分类专栏需要提前创建好。
每个专栏都是一个checkbox,我们可以通过checkbox的value来定位到这个专栏选项。
实现代码如下:
# 分类专栏
categories = csdn_config['categories']
if categories:
for category in categories:
category_input = driver.find_element(By.XPATH, f'//input[@type="checkbox" and @value="{category}"]/..')
category_input.click()
time.sleep(1)