爬虫-(4)

内容概览

  • xpath的使用
  • selenium动作链
  • 自动登录网站
  • 打码平台使用
  • 使用打码平台自动登录
  • 使用selenium爬取信息案例
  • scrapy介绍

xpath的使用

"""
html中选择标签,可以使用的通用方式:
	-css选择
	-xpath选择
		-XPath即为XML路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的语言
"""
  • xpath语法简单介绍

    表达式说明
    nodename选择此节点的所有子节点
    /从根节点选取
    //从匹配选择当前节点选择文档中的节点
    .选取当前节点
    选取当前节点的父节点
    @选取属性
  • 演示案例

    doc='''
    <html>
     <head>
      <base href='http://example.com/' />
      <title>Example website</title>
     </head>
     <body>
      <div id='images'>
       <a href='image1.html' id='id_a'>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'>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]/..')
    # 也可以这样
    # a=html.xpath('//body//a[1]/parent::*')
    # a=html.xpath('//body//a[1]/parent::div')
    # 5 属性匹配
    # a=html.xpath('//body//a[@href="image1.html"]')
    
    # 6 文本获取  text()    ********
    # a=html.xpath('//body//a[@href="image1.html"]/text()')
    
    # 7 属性获取            ******
    # a=html.xpath('//body//a/@href')
    # a=html.xpath('//body//a/@id')
    # # 注意从1 开始取(不是从0)
    # a=html.xpath('//body//a[1]/@id')
    # 8 属性多值匹配
    #  a 标签有多个class类,直接匹配就不可以了,需要用contains
    # a=html.xpath('//body//a[@class="li"]')
    # a=html.xpath('//body//a[@name="items"]')
    # a=html.xpath('//body//a[contains(@class,"li")]')
    # 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()')
    
    # 10 按序选择
    # a=html.xpath('//a[2]/text()')
    # a=html.xpath('//a[3]/@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::*')
    # a=html.xpath('//a[1]/attribute::href')
    # 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]')
    a=html.xpath('//a[1]/following-sibling::*[2]/@href')
    
    print(a)
    
    
    """
    终极大招
    浏览器打开控制台--->右键点击标签--->Copy--->Copy XPath
    """
    

selenium动作链

"""实现网站中需要按住鼠标拖动的效果:滑动验证码"""

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

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
bro.implicitly_wait(8)

try:
    bro.switch_to.frame('iframeResult')  ##切换到iframeResult
    sourse = bro.find_element(by=By.ID, value='draggable')
    target = bro.find_element(by=By.ID, value='droppable')
# # 方式一
#     actions = ActionChains(bro)  # 拿到动作链对象
#     actions.drag_and_drop(sourse, target)  # 把动作放到动作链中,准备串行执行
#     actions.perform()  # 执行
# # 方式二
#     ActionChains(bro).click_and_hold(sourse).perform()  # 按下鼠标
#     distance = target.location['x'] - sourse.location['x']  # 获取两个块之间的距离
#     track = 0
#     while track < distance:
#         ActionChains(bro).move_by_offset(xoffset=2, yoffset=0).perform()  # 每次移动2
#         track += 2
#     ActionChains(bro).release().perform()  # 松开鼠标
except Exception as e:
    print(e)
finally:
    time.sleep(3)
    bro.close()
    bro.quit()

自动登录网站

import time

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

# 检测到了我们使用了selenium控制了浏览器,所以它的滑块出不来;修改配置
options = Options()
options.add_argument("--disable-blink-features=AutomationControlled")  # 去掉自动化控制的提示
bro = webdriver.Chrome(executable_path='./chromedriver.exe', options=options)
bro.implicitly_wait(8)
bro.maximize_window()

bro.get('https://kyfw.12306.cn/otn/resources/login.html')

try:
    username = bro.find_element(by=By.ID, value='J-userName')  # 用户名输入框
    username.send_keys('用户名')
    password = bro.find_element(by=By.ID, value='J-password')  # 密码输入框
    password.send_keys('密码')
    btn = bro.find_element(by=By.ID, value='J-login')  # 登录按钮
    btn.click()
    span = bro.find_element(by=By.ID, value='nc_1_n1z')  # 滑动块
    ActionChains(bro).click_and_hold(span).perform()  # 鼠标按住滑动块
    ActionChains(bro).move_by_offset(xoffset=300, yoffset=0).perform()  # x轴向右滑动300
except Exception as e:
    print(e)
finally:
    time.sleep(3)
    bro.close()
    bro.quit()

打码平台使用

"""如果验证码是图片验证码,我们可以把验证码图片发给第三方,第三方直接把内容返回,我们只需要用钱就可以了"""

使用打码平台自动登录

import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from PIL import Image
from chaojiying import Chaojiying_Client

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.implicitly_wait(8)
bro.maximize_window()

bro.get('http://www.chaojiying.com/apiuser/login/')

try:
    username = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/p[1]/input')
    password = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/p[2]/input')
    code = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/p[3]/input')
    btn = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/p[4]/input')
    username.send_keys('用户名')
    password.send_keys('密码')
    # 获取验证码
    # 1. 将整个页面截图
    bro.save_screenshot('main.png')
    # 2. 获取验证码所在的xy轴坐标
    img = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/div/img')
    location = img.location  # 获取xy轴
    size = img.size  # 获取图片大小
    print(f'location={location},size={size}')
    # 3. 使用pillow截出大图中的验证码
    img_tu = (
        int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height']))
    # 起始坐标加上图的宽和高就是终止坐标
    img = Image.open('./main.png')  # 打开图片
    fram = img.crop(img_tu)  # 裁剪图片
    fram.save('code.png')  # 保存验证码图片
    # 4. 使用打码平台破解
    chaojiying = Chaojiying_Client('用户名', '密码', '96001')  # 用户中心>>软件ID 生成一个替换 96001
    im = open('code.png', 'rb').read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    res_code = chaojiying.PostPic(im,1902)
    print(res_code)
    print(res_code['pic_str'])
except Exception as e:
    print(e)
finally:
    time.sleep(5)
    bro.close()
    bro.quit()

使用selenium爬取信息案例

import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys


def get_goods(bro):
    try:
        goods = bro.find_elements(by=By.CLASS_NAME, value='gl-item')  # 获取所有商品的li标签,结果是一个列表
        print(goods)
        for good in goods:
            name = good.find_element(by=By.CSS_SELECTOR, value='.p-name em').text  # 获取商品名
            price = good.find_element(by=By.CSS_SELECTOR, value='.p-price i').text  # 获取商品价格
            commit = good.find_element(by=By.CSS_SELECTOR, value='.p-commit>strong>a').text  # 获取商品评论数
            url = good.find_element(by=By.CSS_SELECTOR, value='.p-img a').get_attribute('href')  # 获取商品链接
            img = good.find_element(by=By.CSS_SELECTOR, value='.p-img img').get_attribute('src')  # 获取商品图片
            if not img:  # 使用了懒加载,需要判断
                img = 'https://' + good.find_element(by=By.CSS_SELECTOR, value='.p-img img').get_attribute(
                    'data-lazy-img')
            print(f"""
            商品名称:{name}
            商品价格:{price}
            商品链接:{url}
            商品图片:{img}
            商品评论:{commit}
            """)
        btn = bro.find_element(by=By.PARTIAL_LINK_TEXT, value='下一页')  # 下一页按钮
        btn.click()
        time.sleep(1)
        get_goods(bro)  # 递归调用,直到最后一页报错
    except Exception as e:
        print(e)


def spider(url, keyword):
    bro = webdriver.Chrome(executable_path='./chromedriver.exe')
    bro.maximize_window()
    bro.implicitly_wait(8)
    bro.get(url)
    try:
        input_tag = bro.find_element(by=By.ID, value='key')  # 查找到搜索框
        input_tag.send_keys(keyword)
        input_tag.send_keys(Keys.ENTER)  # 输入搜索内容后模拟按下回车键
        get_goods(bro)
    except Exception as e:
        print(e)
    finally:
        time.sleep(3)
        bro.close()
        bro.quit()


if __name__ == '__main__':
    spider('https://www.jd.com/', '手机')  # 传入网址与搜索内容

scrapy介绍

# 前面学的都是模块,做专业的爬虫,可以使用框架 (django:web)  scrapy:爬虫框架
	-做爬虫用的东西,都封装好了,只需要在固定的位置写固定的代码即可


# scrapy 号称爬虫界的djagno
	-django 大而全,做web相关的它都有
    -scrapy 大而全,做爬虫的,它都有


# 介绍
Scrapy一个开源和协作的框架,其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的,使用它可以以快速、简单、可扩展的方式从网站中提取所需的数据。但目前Scrapy的用途十分广泛,可用于如数据挖掘、监测和自动化测试等领域,也可以应用在获取API所返回的数据或者通用的网络爬虫


# 安装 scrapy
	-mac,linux:
    	pip3 install scrapy
    -win:看人品
    	-pip3 install scrapy
    	-人品不好:
        1、pip3 install wheel #安装后,便支持通过wheel文件安装软件   xx.whl
        3、pip3 install lxml
        4、pip3 install pyopenssl
        5、下载并安装pywin32:https://sourceforge.net/projects/pywin32/files/pywin32/
        6、下载twisted的wheel文件:http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted
        7、执行pip3 install 下载目录\Twisted-17.9.0-cp36-cp36m-win_amd64.whl
        8、pip3 install scrapy


 # 释放出scrapy 可执行文件
	-以后使用这个创建爬虫项目 ---》django-admin创建django项目


 # 创建爬虫项目
	scrapy startproject myfirstscrapy


# 创建爬虫 [django创建app]
	cd myfirstscrapy
	scrapy genspider cnblogs www.cnblogs.com


 # 启动爬虫 
	scrapy crawl cnblogs --nolog


 # pycharm中运行
    项目根目录新建run.py
	    from scrapy.cmdline import execute
	    execute(['scrapy', 'crawl', 'cnblogs','--nolog'])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值