前言背景:
等我水够十级我一定会好好回答问题
1.需求分析:
需求:在每一个帖子下回复 ”经验+3“ 然后下一个继续 +3
分析:
-1.贴吧我试过了,它是一个动态的,普通requests拿不到那些有用url, 所以既然要简单所以就不用什么scrapy之类的爬虫框架了,我使用 selenium;
-2.首先要遍历所有的吧内的贴,就得有一个函数专门获取next的url,然后拿到目标url之后,就要解析本页有多少个贴,使用xpath拿到它,得到一个list,然后遍历list进去使用webdriver.Chrome进行元素的操作,该点的点该评论的评论
2.源码实现:
from lxml import etree
from selenium import webdriver
import time
chrome_driver=r"C:\Program Files (x86)\Google\Chrome\81\chromedriver.exe"
header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"}
count_num = 0
count_page = 0
host = "https://tieba.baidu.com"
opt = webdriver.ChromeOptions()
opt.headless = False # 是否隐藏浏览器 True为隐藏
browser = webdriver.Chrome(executable_path=chrome_driver, options=opt)
def browser_of(host_idx, idx):
global host
global count_num
print("本章:"+ host_idx, end=" --- ")
browser.get(host_idx)
re = browser.page_source
html = etree.HTML(re)
urls = html.xpath('//div[@class="threadlist_title pull_left j_th_tit "]/a/@href')
time.sleep(5) # 给扫描时间
print("扫描有{}个贴,准备开始水!".format(len(urls)))
j = 0
for url in urls:
url = host + url
print(url)
browser.get(url)
try:
browser.find_element_by_id("ueditor_replace").click() # 鼠标点击
time.sleep(3)
input_box = browser.find_element_by_id("ueditor_replace")
input_box.send_keys('经验加三,告辞!!!')
j += 1
count_num += 1
print('{0} - 第{1}页 第{2}条 回复成功:经验+3!'.format(count_num, idx, j))
time.sleep(2)
browser.find_element_by_css_selector(".ui_btn.ui_btn_m.j_submit.poster_submit").click()
except Exception as e:
print(e)
print('fail')
time.sleep(5)
return True
def get_to_next_page(host_idx):
global count_page
count_page += 1
print("本页为 = "+host_idx)
browser.get(host_idx)
re = browser.page_source # 获取网页源码
html = etree.HTML(re)
next_url = html.xpath('//div[@id="frs_list_pager"]/a/@href')[-2] # 获取下一页链接
print("下一页 = "+next_url)
# "file://tieba.baidu.com/f?kw=%E6%BB%91%E7%A8%BD&ie=utf-8&pn=50"
if browser_of(host_idx, count_page): # 执行完成
get_to_next_page("https:" + next_url)
browser.close()
if __name__ == '__main__':
host_idx = "https://tieba.baidu.com/f?kw=%E6%BB%91%E7%A8%BD&ie=utf-8&pn=0" # 放置贴吧内第一页url
get_to_next_page(host_idx)
3.源码说明:
- 1.关于selenium:
1.安装: pip install selenium
2.测试是否安装成功:pip show selenium
3.selenium.exe下载:http://npm.taobao.org/mirrors/chromedriver查看自己chrome版本下载
4.查看googlechrome版本:chrome://settings/help - 2.关于代码说明:
1.opt.headless = False # 是否隐藏浏览器 True为隐藏
2. host_idx = “贴吧第一页的链接” #修改为要水贴的吧内的第一页
3.time.sleep(3) #这个最第2s把我测试,太快的话还没开的及回复就跳到下一家水贴了 - 3.关于登录问题:
进入页面时程序睡5s,期间使用鼠标点登录,弹出扫码框时程序不会继续运行,然后扫描登录即可
4.运行效果:
5.关于说明:
1.大量水贴有风险。
2.由于我的账号被封了,所以测试不到最后一次修改的代码是否出bug,如果不能自动转换第二页,请自行修改代码,或者等我解封了再改正吧,哈哈。
2.有的贴吧楼主设置禁止评论或者吧主设置什么的。
2.转载请说明出处!!!
点赞收藏