11_28,selenium定位元素,cookies获取

一。selenium

  selenium+chromedriver

  chrom有界面浏览器下载文件放在根目录

  国内镜像网站地址:http://npm.taobao.org/mirrors/chromedriver/2.38/
  最新的版本去官网找:https://sites.google.com/a/chromium.org/chromedriver/downloads

  selenium可以将一些资源定位:

# 1、find_element_by_id   根据id找
# 2、find_element_by_link_text     根据链接名字找到控件(a标签的文字)
# 3、find_element_by_partial_link_text   根据链接名字找到控件(a标签的文字)模糊查询
# 4、find_element_by_tag_name       根据标签名
# 5、find_element_by_class_name     根据类名
# 6、find_element_by_name           根据属性名
# 7、find_element_by_css_selector   根据css选择器
# 8、find_element_by_xpath          根据xpath选择

  关于百度的登录:

from selenium import webdriver

import time
bro=webdriver.Chrome()
bro.get("http://www.baidu.com")
bro.implicitly_wait(10)
# 1、find_element_by_id   根据id找
# 2、find_element_by_link_text     根据链接名字找到控件(a标签的文字)
# 3、find_element_by_partial_link_text   根据链接名字找到控件(a标签的文字)模糊查询
# 4、find_element_by_tag_name       根据标签名
# 5、find_element_by_class_name     根据类名
# 6、find_element_by_name           根据属性名
# 7、find_element_by_css_selector   根据css选择器
# 8、find_element_by_xpath          根据xpath选择

dl_button=bro.find_element_by_link_text("登录")
dl_button.click()
user_login=bro.find_element_by_id('TANGRAM__PSP_10__footerULoginBtn')
user_login.click()
time.sleep(1)
input_name=bro.find_element_by_name('userName')
input_name.send_keys("18861508055")
input_password=bro.find_element_by_id("TANGRAM__PSP_10__password")
input_password.send_keys("87765396094165")
submit_button=bro.find_element_by_id('TANGRAM__PSP_10__submit')
time.sleep(1)
submit_button.click()

time.sleep(10)

print(bro.get_cookies())
bro.close()

#显示等待和隐示等待
#隐式等待:在查找所有元素时,如果尚未被加载,则等10秒
# browser.implicitly_wait(10)   表示等待所有,

#显式等待:显式地等待某个元素被加载
# wait=WebDriverWait(browser,10)
# wait.until(EC.presence_of_element_located((By.ID,'content_left')))
登录百度

二。使用selenium操作京东爬取链接

from selenium import webdriver
from selenium.webdriver.common.keys import Keys #键盘按键操作
import time
bro=webdriver.Chrome()
bro.get("https://www.jd.com")
bro.implicitly_wait(10)




def get_goods(bro):
    print("------------------------------------")
    goods_li = bro.find_elements_by_class_name('gl-item')
    for good in goods_li:
        img_url = good.find_element_by_css_selector('.p-img a img').get_attribute('src')
        if not img_url:
            img_url = 'https:' + good.find_element_by_css_selector('.p-img a img').get_attribute('data-lazy-img')
        url = good.find_element_by_css_selector('.p-img a').get_attribute('href')
        price = good.find_element_by_css_selector('.p-price i').text
        name = good.find_element_by_css_selector('.p-name em').text.replace('\n', '')
        commit = good.find_element_by_css_selector('.p-commit a').text
        print('''
        商品链接:%s
        商品图片:%s
        商品名字:%s
        商品价格:%s
        商品评论数:%s

        ''' % (url, img_url, name, price, commit))

    next_page = bro.find_element_by_partial_link_text("下一页")
    time.sleep(1)
    next_page.click()
    time.sleep(1)
    get_goods(bro)
input_search=bro.find_element_by_id('key')
input_search.send_keys("性感内衣")
input_search.send_keys(Keys.ENTER)

#进入了另一个页面
try:
    get_goods(bro)
except Exception as e:
    print("结束")
finally:
    bro.close()
爬取京东链接

三,其他操作。获取元素属性等

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys #键盘按键操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素

browser=webdriver.Chrome()

browser.get('https://www.amazon.cn/')

wait=WebDriverWait(browser,10)
wait.until(EC.presence_of_element_located((By.ID,'cc-lm-tcgShowImgContainer')))

tag=browser.find_element(By.CSS_SELECTOR,'#cc-lm-tcgShowImgContainer img')

#获取标签属性,
print(tag.get_attribute('src'))
#获取文本内容
# tag.text

#获取标签ID,位置,名称,大小(了解) print(tag.id) print(tag.location) print(tag.tag_name) print(tag.size) browser.close() 获取标签属性

  模拟浏览器往后退:

#模拟浏览器前进后退
# browser.back()
# time.sleep(10)
# browser.forward()

  cookies管理:

#cookies管理
# print(browser.get_cookies())  获取cookie
# browser.add_cookie({'k1':'xxx','k2':'yyy'})  设置cookie
# print(browser.get_cookies())

  运行js,动作链和选项卡

#运行js
# from selenium import webdriver
# import time
#
# bro=webdriver.Chrome()
# bro.get("http://www.baidu.com")
# bro.execute_script('alert("hello world")') #打印警告
# time.sleep(5)
#选项卡管理
# import time
# from selenium import webdriver
#
# browser=webdriver.Chrome()
# browser.get('https://www.baidu.com')
# browser.execute_script('window.open()')
#
# print(browser.window_handles) #获取所有的选项卡
# browser.switch_to_window(browser.window_handles[1])
# browser.get('https://www.taobao.com')
# time.sleep(3)
# browser.switch_to_window(browser.window_handles[0])
# browser.get('https://www.sina.com.cn')
# browser.close()

#动作链
# from selenium import webdriver
# from selenium.webdriver import ActionChains
#
# from selenium.webdriver.support.wait import WebDriverWait  # 等待页面加载某些元素
# import time
#
# driver = webdriver.Chrome()
# driver.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
# wait=WebDriverWait(driver,3)
# # driver.implicitly_wait(3)  # 使用隐式等待
#
# try:
#     driver.switch_to.frame('iframeResult') ##切换到iframeResult
#     sourse=driver.find_element_by_id('draggable')
#     target=driver.find_element_by_id('droppable')
#
#
# #方式一:基于同一个动作链串行执行
# # actions=ActionChains(driver) #拿到动作链对象
# # actions.drag_and_drop(sourse,target) #把动作放到动作链中,准备串行执行
# # actions.perform()
#
# #方式二:不同的动作链,每次移动的位移都不同
#
#
#     ActionChains(driver).click_and_hold(sourse).perform()
#     distance=target.location['x']-sourse.location['x']
#
#
#     track=0
#     while track < distance:
#         ActionChains(driver).move_by_offset(xoffset=2,yoffset=0).perform()
#         track+=2
#
#     ActionChains(driver).release().perform()
#
#     time.sleep(10)
#
#
# finally:
#     driver.close()

 四。cookies池。

  cookies池就是将众多账号的cookies记录下来,登录的时候随机分配一个cookies,防止ip被封。

  使用selenium获取cookies:

import time
from selenium import webdriver
import json
browser=webdriver.Chrome()
browser.get('https://account.cnblogs.com/signin?returnUrl=https%3A%2F%2Fwww.cnblogs.com%2F')

time.sleep(30)
cookie=browser.get_cookies()
print(cookie)
with open('cookie.json','w')as f:
    json.dump(cookie,f)

  登录博客主页,带上cookies

 

import time
from selenium import webdriver
import json
browser=webdriver.Chrome()
browser.get('https://www.cnblogs.com/')
with open('cookie.json','r')as f:
    di=json.load(f)

cookies = {}
# 获取cookie中的name和value,转化成requests可以使用的形式
for cookie in di:
    cookies[cookie['name']] = cookie['value']
print(cookies)
browser.add_cookie(cookies)
browser.refresh()

time.sleep(10)

  通过requests模块获取(失败):

import requests
with open('cookie.json','r')as f:
    di=json.load(f)

cookies = {}
# 获取cookie中的name和value,转化成requests可以使用的形式
for cookie in di:
    print(cookie)
    for key in cookie.keys():
        cookies[key] = cookie[key]


print(cookies)
res=requests.get('https://i-beta.cnblogs.com/api/user',
             cookies=cookies)

print(res.text)

  需要加上请求头:

import requests
from selenium import webdriver
import time
import json
# 使用selenium打开网址,然后让用户完成手工登录,再获取cookie
url = 'https://account.cnblogs.com/signin?returnUrl=https%3A%2F%2Fwww.cnblogs.com%2F'
driver = webdriver.Chrome()
driver.get(url=url)
time.sleep(50)
driver.refresh()
c = driver.get_cookies()
print(c)
with open('xxx.txt','w') as f:
    json.dump(c,f)
# cookies = {}
# # 获取cookie中的name和value,转化成requests可以使用的形式
# for cookie in c:
#     cookies[cookie['name']] = cookie['value']

# print(cookies)
# driver.quit()
time.sleep(3)
with open('xxx.txt', 'r') as f:
    di = json.load(f)
cookies = {}
# 获取cookie中的name和value,转化成requests可以使用的形式
for cookie in di:
    cookies[cookie['name']] = cookie['value']
print(cookies)
# from datetime import datetime
#
# GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'
#
# # Sun, 24 Nov 2019 06:14:53 GMT
# #Tue, 26 Nov 2019 22:18:23 GMT
# #Sun, 24 Nov 2019 06:14:53 GMT
# # Tue, 26 Nov 2019 14:16:01 GMT (GMT)
# print(datetime.now().strftime(GMT_FORMAT))
# ttt=str(datetime.now().strftime(GMT_FORMAT))
headers = {
    # 'authority': 'www.jd.com',
    # 'method': 'GET',
    # 'path': '/',
    # 'scheme': 'https',
    # 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    # 'accept-encoding': 'gzip, deflate, br',
    # 'accept-language': 'zh-CN,zh;q=0.9',
    # 'cache-control': 'max-age=0',
    # 'upgrade-insecure-requests': '1',
    'authority': 'i-beta.cnblogs.com',
    'method': 'GET',
    'path': '/',
    'scheme': 'https',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cache-control': 'max-age=0',
    'if-modified-since': 'Sun, 24 Nov 2019 06:14:53 GMT',
    # 'if-modified-since': 'Sun, 24 Nov 2019 06:14:53 GMT,
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'none',
    'sec-fetch-user': '?1',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'

}
# 使用该cookie完成请求
response = requests.get(url='https://i-beta.cnblogs.com/api/user', headers=headers, cookies=cookies)
print('xxx')
response.encoding = response.apparent_encoding
print(response.text)
请求头版本

五。破解知乎登录

   破解知乎的基本原理就是读取其中的js代码。其中有运行js代码的模块:

  import execjs     

  还有处理验证码图片的:

 from PIL import Image       

   主要是讲登录信息通过一个加密函数加密,再发送到服务器登录。

#破解知乎登录
from requests_html import HTMLSession     #请求解析库
import base64                             #base64解密加密库
from PIL import Image                     #图片处理库
import hmac                               #加密库
from hashlib import sha1                  #加密库
import time
from urllib.parse import urlencode        #url编码库
import execjs                             #python调用node.js
from http import cookiejar

class Spider():
    def __init__(self):
        self.session = HTMLSession()
        self.session.cookies = cookiejar.LWPCookieJar()    #使cookie可以调用save和load方法
        self.login_page_url = 'https://www.zhihu.com/signin?next=%2F'
        self.login_api = 'https://www.zhihu.com/api/v3/oauth/sign_in'
        self.captcha_api = 'https://www.zhihu.com/api/v3/oauth/captcha?lang=en'
        self.headers = {
            'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER',
        }

        self.captcha =''         #存验证码
        self.signature = ''    #存签名

    # 首次请求获取cookie
    def get_base_cookie(self):
        self.session.get(url=self.login_page_url, headers=self.headers)

    # 处理验证码
    def deal_captcha(self):
        r = self.session.get(url=self.captcha_api, headers=self.headers)
        r = r.json()
        if r.get('show_captcha'):
            while True:
                r = self.session.put(url=self.captcha_api, headers=self.headers)
                img_base64 = r.json().get('img_base64')
                with open('captcha.png', 'wb') as f:
                    f.write(base64.b64decode(img_base64))
                captcha_img = Image.open('captcha.png')
                captcha_img.show()
                self.captcha = input('输入验证码:')
                r = self.session.post(url=self.captcha_api, data={'input_text': self.captcha},
                                      headers=self.headers)
                if r.json().get('success'):
                    break

    def get_signature(self):
        # 生成加密签名
        a = hmac.new(b'd1b964811afb40118a12068ff74a12f4', digestmod=sha1)
        a.update(b'password')
        a.update(b'c3cef7c66a1843f8b3a9e6a1e3160e20')
        a.update(b'com.zhihu.web')
        a.update(str(int(time.time() * 1000)).encode('utf-8'))
        self.signature = a.hexdigest()

    def post_login_data(self):
        data = {
            'client_id': 'c3cef7c66a1843f8b3a9e6a1e3160e20',
            'grant_type': 'password',
            'timestamp': str(int(time.time() * 1000)),
            'source': 'com.zhihu.web',
            'signature': self.signature,
            'username': '+8618953675221',
            'password': 'lqz12345',
            'captcha': self.captcha,
            'lang': 'en',
            'utm_source': '',
            'ref_source': 'other_https://www.zhihu.com/signin?next=%2F',
        }

        headers = {
            'x-zse-83': '3_2.0',
            'content-type': 'application/x-www-form-urlencoded',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER',
        }

        data = urlencode(data)
        with open('ttt.js', 'rt', encoding='utf-8') as f:
            js = execjs.compile(f.read())
        data = js.call('b', urlencode(data))
        print(data)

        r = self.session.post(url=self.login_api, headers=headers, data=data)
        if r.status_code == 201:
            self.session.cookies.save('mycookie')
            print('登录成功')
        else:
            print('登录失败')
    def login(self):
        self.get_base_cookie()
        self.deal_captcha()
        self.get_signature()
        self.post_login_data()

if __name__ == '__main__':
    zhihu_spider = Spider()
    zhihu_spider.login()
破解登录

  python中有讲链接后面的码转化成中文的模块。

# from requests_html import HTMLSession
# session = HTMLSession()
# res=session.get("http://python-requests.org/")
# # res.html.render()
# print(res.html)
from urllib.parse import unquote_plus  #字符转中文
from urllib.parse import urlencode  #中文转字符
msg = '''
"client_id=c3cef7c66a1843f8b3a9e6a1e3160e20&grant_type=password&timestamp=1574838172749&source=com.zhihu.web&signature=d9ca5ecd24ebcfd42360eabd392d860e837005d8&username=%2B8618953675221&password=lqz12345&captcha=&lang=cn&utm_source=&ref_source=other_https%3A%2F%2Fwww.zhihu.com%2Fsignin%3Fnext%3D%252F"
'''
print(unquote_plus(msg))
View Code

六。xpath的使用。

  xpath是一个处理xml文件的工具,需要和css联合使用:

doc='''
<html>
 <head>
  <base href='http://example.com/' />
  <title>Example website</title>
 </head>
 <body>
  <div id='images'>
   <a href='image1.html' a="xxx">Name: My image 1 <br /><img src='image1_thumb.jpg' /></a>
   <a href='image2.html'>Name: My image 2 <br /><img src='image2_thumb.jpg' /></a>
   <a href='image3.html'>Name: My image 3 <br /><img src='image3_thumb.jpg' /></a>
   <a href='image4.html' class='li'>Name: My image 4 <br /><img src='image4_thumb.jpg' /></a>
   <a href='image5.html' class='li li-item' name='items'>Name: My image 5 <br /><img src='image5_thumb.jpg' /></a>
   <a href='image6.html' name='items'><span><h5>test</h5></span>Name: My image 6 <br /><img src='image6_thumb.jpg' /></a>
  </div>
 </body>
</html>
'''
from lxml import etree

html=etree.HTML(doc)
# html=etree.parse('search.html',etree.HTMLParser())
# 1 所有节点
a=html.xpath('//*')    #匹配所有标签
# 2 指定节点(结果为列表)
# a=html.xpath('//head')
# 3 子节点,子孙节点
a=html.xpath('//div/a')
a=html.xpath('//body/a') #无数据
a=html.xpath('//body//a')
# 4 父节点
# a=html.xpath('//body//a[@href="image1.html"]/..')
a=html.xpath('//body//a[1]/..')  #从1开始
# 也可以这样
a=html.xpath('//body//a[1]/parent::*')
# 5 属性匹配
a=html.xpath('//body//a[@href="image1.html"]')

# 6 文本获取
a=html.xpath('//body//a[@href="image1.html"]/text()')
a=html.xpath('//body//a/text()')

# 7 属性获取
# a=html.xpath('//body//a/@href')
# # 注意从1 开始取(不是从0)
a=html.xpath('//body//a[2]/@href')
# 8 属性多值匹配
#  a 标签有多个class类,直接匹配就不可以了,需要用contains
# a=html.xpath('//body//a[@class="li"]')
a=html.xpath('//body//a[contains(@class,"li")]/text()')
# a=html.xpath('//body//a[contains(@class,"li")]/text()')
# 9 多属性匹配
a=html.xpath('//body//a[contains(@class,"li") or @name="items"]')
a=html.xpath('//body//a[contains(@class,"li") and @name="items"]/text()')
a=html.xpath('//body//a[contains(@class,"li")]/text()')
# 10 按序选择
a=html.xpath('//a[2]/text()')
a=html.xpath('//a[2]/@href')
# 取最后一个
a=html.xpath('//a[last()]/@href')
# 位置小于3的
a=html.xpath('//a[position()<3]/@href')
# 倒数第二个
a=html.xpath('//a[last()-2]/@href')
# 11 节点轴选择
# ancestor:祖先节点
# 使用了* 获取所有祖先节点
a=html.xpath('//a/ancestor::*')
# # 获取祖先节点中的div
a=html.xpath('//a/ancestor::div')
# attribute:属性值
a=html.xpath('//a[1]/attribute::*')
# child:直接子节点
a=html.xpath('//a[1]/child::*')
# descendant:所有子孙节点
a=html.xpath('//a[6]/descendant::*')
# following:当前节点之后所有节点
a=html.xpath('//a[1]/following::*')
a=html.xpath('//a[1]/following::*[1]/@href')
# following-sibling:当前节点之后同级节点
a=html.xpath('//a[1]/following-sibling::*')
a=html.xpath('//a[1]/following-sibling::a')
a=html.xpath('//a[1]/following-sibling::*[2]/text()')
a=html.xpath('//a[1]/following-sibling::*[2]/@href')

print(a)

 

posted on 2019-11-28 00:25  一只萌萌哒的提莫  阅读(217)  评论(0编辑  收藏  举报