python爬虫-使用selenium自动登录微博

环境准备:anaconda、pycharm编辑器、chromedriver(记得下载)
首先查看本地anaconda的python环境和selenium版本号(不同版本的api接口可能不同)

conda list python

输出

# Name                    Version                   Build  Channel
ipython                   8.12.0          py311hecd8cb5_0  
ipython_genutils          0.2.0              pyhd3eb1b0_1  
msgpack-python            1.0.3           py311ha357a0b_0  
python                    3.11.3               h1fd4e5f_0  
python-dateutil           2.8.2              pyhd3eb1b0_0  
python-fastjsonschema     2.16.2          py311hecd8cb5_0  
python-json-logger        2.0.7           py311hecd8cb5_0  
python-libarchive-c       2.9                pyhd3eb1b0_1  
python-lmdb               1.4.1           py311hcec6c5f_0  
python-lsp-black          1.2.1           py311hecd8cb5_0  
python-lsp-jsonrpc        1.0.0              pyhd3eb1b0_0  
python-lsp-server         1.7.2           py311hecd8cb5_0  
python-slugify            5.0.2              pyhd3eb1b0_0  
python-snappy             0.6.1           py311hcec6c5f_0  
python.app                3               py311h6c40b1e_0  

我的python版本是3.11.3,所以我默认下载的selenium版本号是 selenium 4.11.2

自动登录的python脚本代码如下:

import time
from selenium import webdriver
from selenium.webdriver.common.by import By

def csv_writer(item):
    with open("weibo.csv", "a", newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(item)

def login():
    driver.get("https://weibo.com/login.php")
    time.sleep(5)
    # 旧版本的接口是driver.find_element_by_id,自行更改
    username = driver.find_element(by=By.ID, value="loginname")
    username.send_keys('此处换成你自己的用户名')
    time.sleep(3)
    password = driver.find_element(by=By.NAME, value="password")
    password.send_keys('此处换成你自己的密码')
    time.sleep(3)
    submit = driver.find_element(by=By.XPATH, value='//*[@class="W_btn_a btn_32px"]')
    submit.click()
    time.sleep(3600)

if __name__ == "__main__":
    driver = webdriver.Chrome()
    login()
    time.sleep(3600)

最后运行这个脚本文件即可自动登录微博

你可能感兴趣的:(python,爬虫,selenium)