selenium与修改user-agent请求头
爬微信的时候部分内容受限,例如下图链接,微信企业号应用考勤打卡只接受微信客户端打开,仅需修改请求头中的user agent、伪装微信浏览器。
修改user agent的3种方法:
- 浏览器扩展程序/插件:chrome网上应用商店需要翻墙,较为困难;网上下载的user-agent-switcher也可能由于浏览器版本不同而导致无法使用。火狐应用商店可以下载插件,但试了几个都不能自定义。
- F12网页开发者工具:More tools-Network conditions-下方User agent取消勾选slect automatically-Custom…-填入需要的user agent。但每次开新的网页需要重新勾选。
- 直接代码修改:selenium中的chrome webdriver只需新增一行chromeOptions.add_argument(‘相应user agent’);如果是request或scrapy还可以设定请求头中的其他参数。
微信user agent参考:
https://zhangzifan.com/wechat-user-agent.html
https://blog.csdn.net/weixin_46767352
代码:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import schedule
import time
def parse_page():
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument('user-agent="Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B176 MicroMessenger/4.3.2"') #修改user agent
browser = webdriver.Chrome(chrome_options=chromeOptions) # browser = webdriver.Chrome()
#browser.set_page_load_timeout(10)
wait = WebDriverWait(browser, 10) # 设置隐式等待时间
browser.get('https://m.ruc.edu.cn/uc/wap/login?redirect=https%3A%2F%2Fm.ruc.edu.cn%2Fuc%2Fapi%2Foauth%2Fdefault%3Fredirect%3Dhttp%253A%252F%252Fxs.ruc.edu.cn%252Ffx%252Findex%252Fcallback%26appid%3D200200519175100346%26state%3Dhttp%253A%252F%252Fxs.ruc.edu.cn%252Ffx%252Fstudents%252Fjump') #网址
# 学号
name_input = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div[2]/div[1]/input')))
name_input.clear()
name_input.send_keys('学号')
# 密码
code_input = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div[2]/div[2]/input')))
code_input.clear()
code_input.send_keys('密码')
# 登录
submit = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div[3]')))
submit.click()
# 确定
submit = wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/section[2]/div[2]/a')))
submit.click()
# 体温
temp_input = wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div/div[2]/div[2]/form/div/div/label[1]/input ')))
temp_input.clear()
temp_input.send_keys('36')
# 打卡
submit = wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div/div[2]/div[2]/form/div/div/input')))
submit.click()
# 清除缓存,退出
#browser.quit()
# 定时
schedule.every().day.at("07:01").do(parse_page)
while True:
schedule.run_pending()
time.sleep(1)