Python extra: use selenium to automatically like CSDN blog posts

Hello everyone, I’m wanzirui32, today we will learn how to use selenium to like CSDN blog posts. This is my 40th blog post. Please support me!

1. Log in

CSDN login has been introduced in the previous article , if you don’t know, you can go and see!

2. Like

2.1 Analysis

Here is an analysis of my article:
Like analysis
According to the above analysis, we can write a piece of code.

2.2 Writing code

Code: (look at the comments if you don’t understand)

from selenium.webdriver import Firefox
from time import sleep

def csdn_login(driver, username, password):
	# 此处省略登录函数 可以去上一篇复制过来

# 需要点赞的文章
url = 'https://blog.csdn.net/wangzirui32/article/details/113815878'

# 把executable_path设置为你电脑内浏览器驱动的位置目录
driver = Firefox(executable_path="geckodriver.exe")
csdn_login(driver, "你的用户名", "你的密码")
# 等待3秒是为了等待CSDN上传登录数据
sleep(3)
# 请求文章页面
driver.get(url)

# 获取id为is-like的li标签
# 点赞链接的所在处
li = driver.find_element_by_xpath("//li[@id='is-like']")
# 找到a标签
a = li.find_element_by_tag_name("a")
# 获取id为is-like-span的标签 可以根据标签内容用来判断是否已经点赞
span = a.find_element_by_id("is-like-span")

# 如果它的内容为“已赞”
if span.text == "已赞":
    print("此文章已经点赞!")
else:
	# 点击a标签
	a.click()
    print("点赞操作完成!")

# 关闭窗体
driver.close()

Here is a point. The reason why we don't directly search for the a tag is because it has no attributes and is not easy to find, so we have to narrow the search scope to the li tag.

Write at the end

This program can actually be improved, such as setting a for loop in the code, traversing a list, storing the URLs of many articles in the list, and achieving the function of giving multiple blog posts likes (Tips: You can climb on the CSDN ranking Get the article URL)


Today's course is over here. Those who are interested can like and collect, bye bye!

Guess you like

Origin blog.csdn.net/wangzirui32/article/details/113846674