话不多说,上示例代码
from selenium import webdriver
import time
chromedriver = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe"
#设置不加载图片
chrome_opt = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images": 2}
chrome_opt.add_experimental_option("prefs", prefs)
dirver = webdriver.Chrome(executable_path=chromedriver, chrome_options=chrome_opt)
dirver.get("https://www.zhihu.com/signup?next=%2F")
#获取页面HTML
html = driver.page_source
dirver.find_element_by_xpath("//div[@class='SignContainer-switch']/span").click()
dirver.find_element_by_xpath("//div[@class='SignFlow-accountInput Input-wrapper']/input").send_keys("")
dirver.find_element_by_xpath("//div[@class='SignFlow-password']/div/div[@class='Input-wrapper']/input").send_keys("")
dirver.find_element_by_xpath("//button[@class='Button SignFlow-submitButton Button--primary Button--blue']").click()
cookie = [item["name"] + "=" + item["value"] for item in dirver.get_cookies()]
cookiestr = ';'.join(item for item in cookie)
print(cookiestr)
上述代码是登录知乎的示例,
其中,send_keys("")
填写的是用户名和密码。
首先点击find_element_by_xpath("//div[@class='SignContainer-switch']/span")
这个元素切换到输入用户名和密码的界面,
然后使用xpath找到用户名和密码的元素位置,执行send_keys("")
方法填充用户名和密码,
最后找到登录按钮,执行点击动作。
cookie = [item["name"] + "=" + item["value"] for item in dirver.get_cookies()]
这行代码是获取登录后的cookie。
js = 'function scroll(){var scrollElem=document.scrollingElement;scrollElem.scrollTop = len;le = document.scrollingElement.scrollTop;He = document.scrollingElement.scrollHeight;cl = document.scrollingElement.clientHeight;if(le + cl == He&&le + cl!=0) {}len=len+300;setTimeout(scroll,500)};len = 0;scroll();'
driver.execute_script(js)
上边两行代码是执行js脚本使界面自动下拉滚动。