python analog browser to open the Baidu home page and log in, or click and save the page Home News

First, I do not know how to simulate open shoes browser's look at my last article: http: //blog.csdn.net/Trisyp/article/details/78688106
This article relates to pre-configured, so it will not be sure of view, the configuration is over after further study of this article

this article main function is to simulate login Baidu account; or click Home News, at the same time save and print the page source
process is not to say, I try to have added notes, direct attached on Code:

simulated landing complete code is as follows:

from selenium import webdriver
import os
import time


#构造模拟浏览器
chromedriver = "C:/Program Files (x86)/Google/Chrome/Application/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver) #模拟打开浏览器
time.sleep(2)
url = "https://www.baidu.com/"
driver.get(url) #打开网址
# driver.maximize_window() #窗口最大化

#模拟登陆
time.sleep(2)
#driver.find_element_by_name('tj_login').click() #这样写报错:元素不可见,所以用万能的Xpath
driver.find_element_by_xpath('//*[@id="u1"]/a[7]').click() #点击登录按钮
time.sleep(2)
driver.find_element_by_name('userName').clear() #先清除输入框内容
driver.find_element_by_name('userName').send_keys(u'000000') #输入账号
time.sleep(1)
driver.find_element_by_name('password').clear()
driver.find_element_by_name('password').send_keys(u'000000') #输入密码
#因为需要验证码,所以输完账号密码之后就自己手动输入验证码(能力有限,目前还只能手动解决)


News Click complete code is as follows:

from selenium import webdriver
import os
import time


#构造模拟浏览器
chromedriver = "C:/Program Files (x86)/Google/Chrome/Application/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver) #模拟打开浏览器
time.sleep(2)
url = "https://www.baidu.com/"
driver.get(url) #打开网址
# driver.maximize_window() #窗口最大化

#模拟登陆
time.sleep(2)
driver.find_element_by_xpath('//*[@id="u1"]/a[1]').click()
time.sleep(2)
html = driver.page_source
print(html)


# As Xpath acquisition we should all know, there is also the method of stickers (to the Home News for example): After entering the Baidu home page, right-click on news selection examination to enter into Developer mode, and then navigate to the news corresponding page elements (ie elements), select the copy right of the page elements you can see there are several options, select the copy Xpath on the line, and then copied to your code.

 

Published 49 original articles · won praise 95 · Views 230,000 +

Guess you like

Origin blog.csdn.net/Trisyp/article/details/78712715