news 2026/6/23 20:13:06

我用Python写了个脚本,每天自动发100条外链,SEO流量暴涨300%

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
我用Python写了个脚本,每天自动发100条外链,SEO流量暴涨300%

前言:为什么我要折腾这个

最近在做SEO优化,发现手动去各个平台发外链真的太累了。Reddit发一圈、Quora答几个问题、各种论坛注册发帖… 一天下来手都要废了。

作为一个会写代码的独立开发者,我就想:这种重复劳动,为什么不让机器来做呢?

于是就有了这篇文章。今天教大家用Playwright来实现自动发外链。

为什么选Playwright而不是Selenium?

说实话,我之前一直用Selenium,但后来发现Playwright真的香:

  • 速度更快- 启动浏览器、执行操作都比Selenium快
  • API更现代- async/await支持,代码写起来舒服
  • 更稳定- 自动等待机制做得很好,不用到处写sleep
  • 多浏览器支持- Chromium、Firefox、WebKit都能用

最关键的是,文档写得清楚,遇到问题Google一下基本都能解决。

环境准备

首先装一下Playwright。我用的是Python,因为写起来快:

pipinstallplaywright playwrightinstallchromium

这个playwright install chromium会下载浏览器,第一次可能要等一会儿,喝杯咖啡就好了。

第一个例子:自动登录Reddit

我们先从简单的开始,实现自动登录Reddit。

fromplaywright.sync_apiimportsync_playwrightimporttimedeflogin_reddit(username,password):withsync_playwright()asp:# 启动浏览器,headless=False可以看到浏览器操作browser=p.chromium.launch(headless=False)page=browser.new_page()# 打开Reddit登录页page.goto('https://www.reddit.com/login/')# 等待页面加载page.wait_for_load_state('networkidle')# 填写用户名page.fill('input[name="username"]',username)# 填写密码page.fill('input[name="password"]',password)# 点击登录按钮page.click('button[type="submit"]')# 等待登录完成time.sleep(3)print("登录成功!")# 保持浏览器打开,方便调试input("按回车关闭浏览器...")browser.close()# 使用示例login_reddit('your_username','your_password')

几个要注意的点:

  1. headless=False- 开发的时候一定要设成False,能看到浏览器在干什么,方便调试
  2. wait_for_load_state- 等待页面加载完成,不然可能找不到元素
  3. 选择器 -input[name="username"]这种CSS选择器,用浏览器的开发者工具很容易找到

进阶:自动发帖到Reddit

登录搞定了,接下来发帖:

defpost_to_reddit(username,password,subreddit,title,content,link):withsync_playwright()asp:browser=p.chromium.launch(headless=False)context=browser.new_context()page=context.new_page()# 先登录page.goto('https://www.reddit.com/login/')page.wait_for_load_state('networkidle')page.fill('input[name="username"]',username)page.fill('input[name="password"]',password)page.click('button[type="submit"]')# 等待登录完成page.wait_for_url('https://www.reddit.com/',timeout=10000)print("登录成功")# 去到指定的subredditpage.goto(f'https://www.reddit.com/r/{subreddit}/submit')page.wait_for_load_state('networkidle')# 选择发帖类型(Link)page.click('button[data-name="link"]')time.sleep(1)# 填写标题page.fill('textarea[name="title"]',title)# 填写链接page.fill('input[name="url"]',link)# 填写内容(如果有)ifcontent:page.fill('div[contenteditable="true"]',content)# 点击发布page.click('button:has-text("Post")')# 等待发布完成time.sleep(3)print("发帖成功!")input("按回车关闭...")browser.close()# 使用示例post_to_reddit(username='your_username',password='your_password',subreddit='webdev',title='Check out my new tool!',content='I built this cool thing...',link='https://yoursite.com')

实战技巧:处理各种坑

1. 反爬虫检测

很多网站会检测你是不是机器人。几个应对方法:

# 使用真实的User-Agentcontext=browser.new_context(user_agent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36')# 随机延迟importrandom time.sleep(random.uniform(2,5))# 模拟人类行为:滚动页面page.evaluate('window.scrollBy(0, 300)')time.sleep(1)page.evaluate('window.scrollBy(0, 300)')

2. 保存登录状态

每次都登录太慢了,可以保存cookies:

# 登录后保存cookiescontext.storage_state(path="reddit_auth.json")# 下次直接加载context=browser.new_context(storage_state="reddit_auth.json")

3. 处理验证码

这个是最麻烦的。我的做法:

# 检测是否出现验证码ifpage.locator('iframe[title*="recaptcha"]').count()>0:print("检测到验证码,请手动完成")input("完成后按回车继续...")

就是让程序暂停,我手动点一下验证码,然后继续。虽然不够自动化,但对于小规模使用够了。

4. 错误处理

一定要加try-except,不然跑到一半挂了很烦:

try:page.click('button[type="submit"]',timeout=5000)exceptExceptionase:print(f"点击失败:{e}")page.screenshot(path="error.png")# 截图保存现场raise

完整的外链发布脚本

把上面的东西整合一下,做一个能批量发外链的脚本:

fromplaywright.sync_apiimportsync_playwrightimporttimeimportrandomimportjsonclassLinkPoster:def__init__(self,headless=False):self.headless=headless self.browser=Noneself.context=Nonedefstart(self):"""启动浏览器"""self.playwright=sync_playwright().start()self.browser=self.playwright.chromium.launch(headless=self.headless)self.context=self.browser.new_context(user_agent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36')defclose(self):"""关闭浏览器"""ifself.browser:self.browser.close()ifself.playwright:self.playwright.stop()defrandom_delay(self,min_sec=2,max_sec=5):"""随机延迟,模拟人类操作"""time.sleep(random.uniform(min_sec,max_sec))deflogin_reddit(self,username,password):"""登录Reddit"""page=self.context.new_page()try:page.goto('https://www.reddit.com/login/')page.wait_for_load_state('networkidle')page.fill('input[name="username"]',username)self.random_delay(1,2)page.fill('input[name="password"]',password)self.random_delay(1,2)page.click('button[type="submit"]')page.wait_for_url('https://www.reddit.com/',timeout=10000)# 保存登录状态self.context.storage_state(path="reddit_auth.json")print("✓ Reddit登录成功")page.close()returnTrueexceptExceptionase:print(f"✗ Reddit登录失败:{e}")page.screenshot(path="reddit_login_error.png")page.close()returnFalsedefpost_reddit(self,subreddit,title,link,comment=""):"""在Reddit发帖"""page=self.context.new_page()try:# 去发帖页面page.goto(f'https://www.reddit.com/r/{subreddit}/submit')page.wait_for_load_state('networkidle')self.random_delay()# 选择Link类型page.click('button[data-name="link"]')self.random_delay(1,2)# 填写内容page.fill('textarea[name="title"]',title)self.random_delay(1,2)page.fill('input[name="url"]',link)self.random_delay(1,2)ifcomment:page.fill('div[contenteditable="true"]',comment)self.random_delay(1,2)# 发布page.click('button:has-text("Post")')self.random_delay(3,5)print(f"✓ 成功发布到 r/{subreddit}")page.close()returnTrueexceptExceptionase:print(f"✗ 发布到 r/{subreddit}失败:{e}")page.screenshot(path=f"reddit_post_error_{subreddit}.png")page.close()returnFalsedefbatch_post(self,posts_config):"""批量发帖"""success_count=0fail_count=0fori,postinenumerate(posts_config,1):print(f"\n[{i}/{len(posts_config)}] 正在发布...")ifself.post_reddit(subreddit=post['subreddit'],title=post['title'],link=post['link'],comment=post.get('comment','')):success_count+=1else:fail_count+=1# 每次发帖后随机等待,避免被限制ifi<len(posts_config):wait_time=random.uniform(30,60)print(f"等待{wait_time:.1f}秒后继续...")time.sleep(wait_time)print(f"\n完成! 成功:{success_count}, 失败:{fail_count}")# 使用示例if__name__=="__main__":# 配置要发布的内容posts=[{'subreddit':'SideProject','title':'Built a tool to automate my workflow','link':'https://yoursite.com','comment':'Hey everyone, I built this tool to solve...'},{'subreddit':'webdev','title':'New dev tool for productivity','link':'https://yoursite.com','comment':'As a solo developer, I found...'}]# 创建发布器poster=LinkPoster(headless=False)poster.start()try:# 先登录poster.login_reddit('your_username','your_password')# 批量发帖poster.batch_post(posts)finally:poster.close()

一些使用建议

1. 不要太频繁

每个平台都有发帖频率限制。Reddit一般建议:

  • 新账号:每天1-2个帖子
  • 老账号:每小时不超过1个
  • 不同subreddit之间间隔30分钟以上

2. 内容要有价值

自动化只是工具,内容质量才是关键。不要发垃圾信息,会被封号的。

3. 多账号轮换

准备几个账号轮流用,不要一个账号发太多。可以这样改代码:

accounts=[{'username':'account1','password':'pass1'},{'username':'account2','password':'pass2'},]foraccountinaccounts:poster.login_reddit(account['username'],account['password'])# 发一部分帖子poster.batch_post(posts[:2])time.sleep(3600)# 换账号前等1小时

4. 记录日志

加个日志功能,方便追踪:

importlogging logging.basicConfig(filename='link_posting.log',level=logging.INFO,format='%(asctime)s - %(message)s')# 在发帖成功后logging.info(f"成功发布到 r/{subreddit}:{title}")

其他平台怎么办?

同样的思路可以用到其他平台:

Quora:

# 找到"回答问题"按钮page.click('button:has-text("Answer")')# 填写答案page.fill('div[contenteditable="true"]',your_answer)

Medium:

# 点击"Write"page.click('a[href="/new-story"]')# 填写标题和内容page.fill('h1[data-default-text="Title"]',title)page.fill('p[data-default-text="Tell your story..."]',content)

HackerNews:

# 提交链接page.goto('https://news.ycombinator.com/submit')page.fill('input[name="title"]',title)page.fill('input[name="url"]',url)page.click('input[type="submit"]')

核心就是:

  1. 打开开发者工具
  2. 找到对应的输入框和按钮
  3. 用Playwright模拟操作

最后的碎碎念

这个工具我自己用了一段时间,确实省了不少时间。但说实话,最重要的还是:

  • 内容质量- 垃圾内容发再多也没用
  • 适度使用- 不要滥用,容易被封
  • 持续优化- 根据效果调整策略

自动化只是让你有更多时间去做更重要的事情,比如优化产品、写更好的内容。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/23 15:52:26

剧透 2026 年第一个值得你奔赴现场的 AI 大会

以下文章来源于谷歌云服务&#xff0c;作者 Google CloudAI 驱动&#xff0c;智胜全球2026 年 1 月 15 日 北京Google Cloud 出海峰会即将开幕2026 年&#xff0c;AI 正从 "技术尝鲜" 走向 "规模化落地"。对于出海企业而言&#xff0c;这不再是一道选择题&…

作者头像 李华
网站建设 2026/6/23 15:54:45

解锁地理智能:ArcGIS API for Python 全栈开发实战指南

在当今数据驱动的世界中&#xff0c;地理空间分析已成为各行各业决策的重要支撑。然而&#xff0c;传统GIS软件往往操作复杂、学习曲线陡峭&#xff0c;让许多开发者和数据分析师望而却步。ArcGIS API for Python应运而生&#xff0c;它将专业级GIS功能封装成简洁的Python接口&…

作者头像 李华
网站建设 2026/6/22 23:31:22

零基础掌握Agent Zero多语言配置:打破语言壁垒的完整指南

零基础掌握Agent Zero多语言配置&#xff1a;打破语言壁垒的完整指南 【免费下载链接】agent-zero Agent Zero AI framework 项目地址: https://gitcode.com/GitHub_Trending/ag/agent-zero 还在为AI工具界面语言不匹配而烦恼吗&#xff1f;想要团队中的每个成员都能用母…

作者头像 李华
网站建设 2026/6/23 17:56:07

Wan2GP 完整使用指南:从零开始掌握开源视频生成技术

Wan2GP 是一个专为GPU性能有限的用户设计的开源视频生成模型套件&#xff0c;支持Wan系列、Hunyuan Video和LTV Video等多种先进模型。这个强大的工具让任何人都能在消费级硬件上创造高质量的视频内容&#xff0c;真正实现了"让每个人都能创作视频"的愿景。 【免费下…

作者头像 李华
网站建设 2026/6/23 13:31:37

如何申请EmotiVoice商用授权许可?

如何申请 EmotiVoice 商用授权许可 在虚拟主播一夜爆红、AI 配音席卷短视频平台的今天&#xff0c;语音合成技术早已不再是实验室里的冷门研究。用户对“像人一样说话”的 AI 声音越来越挑剔——他们不要机械朗读&#xff0c;而要能哭会笑、有情绪起伏的声音。正是在这种需求驱…

作者头像 李华
网站建设 2026/6/23 17:56:27

【2025年华为秋招(AI)-12月17日-第二题(200分)- 使用线性回归预测手机售价】(题目+思路+JavaC++Python解析+在线测试)

题目内容 手机的售价跟手机的软硬件特性有关系。硬件规格越高、软件特性越丰富,则手机给消费者提供的价值越大,同时手机的售价越高。我们在市面上收集了若干款手机,从硬件能力、系统流畅度、 A I AI AI能力 3 3 3个方面对这些手机进行打分,并记录这些手机的分数和售价。请…

作者头像 李华