python爬虫selenium+scrapy常用功能笔记

这篇具有很好参考价值的文章主要介绍了python爬虫selenium+scrapy常用功能笔记。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Selenium

常用包的导入

import re ,time ,json,os,random

from selenium import webdriver  # 导入 webdriver
from selenium.webdriver.common.keys import Keys  # 要想调用键盘按键操作需要引入keys包 比如 回车和ctrl键
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait  # WebDriverWait 库,负责循环等待
from selenium.webdriver.support import expected_conditions as EC  # expected_conditions 类,负责条件出发

# 下面是解析和sql存储用的工具
from lxml import etree
from pymysql import *

初始化配置 和 特征隐藏

chrome_options = Options()
# chrome_options.add_argument("--headless")  # 设置为无头浏览器
chrome_options.add_argument("log-level=3") # 禁止掉浏览器调试的提示信息 有些网站console.log太多了
chrome_options.add_argument("disable-blink-features=AutomationControlled")  # 这一行告诉chrome去掉机器人痕迹
# 下面两行也可以手动去一部分
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
chrome_options.add_experimental_option('useAutomationExtension', False)
# executable_path 后值为驱动所在位置
driver = webdriver.Chrome(executable_path="chromedriver.exe",options=chrome_options)
start_url = "https://bot.sannysoft.com/"
# 打开并访问网页
driver.get(start_url)

机器人特征检验

访问网址可以看到直观结果

https://bot.sannysoft.com/

显(隐)式等待

# 隐式等待
WebDriverWait(driver, 8).until(
        EC.presence_of_element_located(
            (By.XPATH, "//div[@class='job-list']//ul//li"))  # 通过XPATH查找
    )
    
# 显式等待
driver.implicitly_wait(0.2)

页面操作

获取页面dom

page_source = driver.page_source

页面元素获取

# 单一样式搜索
page_content = etree.HTML(driver.page_source)
content_now_page = page_content.xpath("//div[@class='job-list']//ul//li")
next_url =  response.xpath("(//div[@class='page_al']//a)[last()-1]/@href").get()

# 多样式选择搜索  div[contains(@class,'job-limit')]
# 使用括号包裹可以控制优先级 看情况使用
yao_qiu = page_content.xpath("(.//div[contains(@class,'job-limit')])//text()")

元素点击

element_next.click()

frame跳转

driver.switch_to.frame('editormd-image-iframe')

获取cookie

cookie = driver.get_cookies()
 # print("这是请求到的原始cookie",cookie)
cookies_list = []
for cookie_dict in cookie:
    cookie = cookie_dict['name'] + '=' + cookie_dict['value']
    cookies_list.append(cookie)
# print("拼接后的cookir",cookies_list)
cookies = ';'.join(cookies_list)

给请求添加cookie

driver.add_cookie({"name":"_identity","value":"d192e16b"})

事件操作

点击

driver.find_element(By.CLASS_NAME,'add-img').click()

上传文件

driver.find_element(By.NAME,'editormd-image-file').send_keys(r"D:\img2.png")

退出页面

driver.quit()

Scrapy

多摘自之前文档
https://blog.csdn.net/weixin_43521165/article/details/111905800

初始创建命令

创建项目
scrapy startproject 爬虫项目名字 # 例如 scrapy startproject fang_spider
scrapy genspider 爬虫名字 ‘域名’ #例如 scrapy genspider fang ‘fang.com’

# 设置启动文件 在项目目录下建立就行 写入以下代码以后直接运行则可以启动爬虫
# 这里第二行的 fang 是你创建的爬虫的名字
from scrapy import cmdline
cmdline.execute("scrapy crawl fang".split())

常用请求头

需要更多可以点击去这里复制http://www.useragentstring.com

user_agent = [
        "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
        "Mozilla/5.0 (X11; Ubuntu; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2919.83 Safari/537.36",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2762.73 Safari/537.36",
        "ozilla/5.0 (X11; Ubuntu; Linux i686 on x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2820.59 Safari/537.36"
        ]

Parse解析

手动去重过滤

scrapy本身有链接去重功能,同样的链接不会重复访问。但是有些网站是在你请求A的时候重定向到B,重定向到B的时候又给你重定向回A,然后才让你顺利访问,此时scrapy由于默认去重,这样会导致拒绝访问A而不能进行后续操作.

解决方式:
在yield访问新链接时,加上 dont_filter=True 参数,不让它自动过滤

 yield scrapy.Request(url=response.urljoin(next_url),callback=self.esf_parse,dont_filter=True)

meta传参

 yield scrapy.Request(url=response.urljoin(next_url),headers=cooki,callback=self.esf_parse,
 					meta={'info':("123456", city), 'cooki':cooki})

获取请求或者响应的cookie

# 获取请求的cookie
Cookie = response.request.headers.getlist('Cookie')  # 请求
# 获取相应的cookie
Cookie2 = response.headers.getlist('Set-Cookie')  # 响应
print(Cookie,'111cookoooo222:',Cookie2)

piplines.py 异步入库

只需要更改数据库的配置 item元素的获取 和 sql语句即可文章来源地址https://www.toymoban.com/news/detail-419367.html

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from twisted.enterprise import adbapi
from pymysql import cursors

class newFangSpiderPipeline:
    x = 0
    def __init__(self):
        dbparams = {
            'host': '127.0.0.1',
            'port': 3306,
            'user': 'root',
            'password': 'password',
            'database': 'fangtianxia',
            'charset': 'utf8',
            'cursorclass': cursors.DictCursor
        }
        self.dbpool = adbapi.ConnectionPool('pymysql', **dbparams)
        self._sql = None

    @property
    def sql(self):
        self.x += 1
        print('*-*' * 10, '第{}条数据进来了++++++'.format(self.x))
        if not self._sql:
            self._sql = """
            insert into newhouse(id,name ,province,city,price,areas,state ,style, address,ori_url) values
             (null,%s,%s,%s,%s,%s,%s,%s,%s,%s)
            """
            return self._sql
        return self._sql

    def process_item(self, item, spider):
        defer = self.dbpool.runInteraction(self.insert_item, item)
        defer.addErrback(self.handle_error, item, spider)

    def insert_item(self, cursor, item):
        cursor.execute(self.sql, (
        item['name'], item['province'], item['city'], item['price'], item['areas'], item['state'],
        item['style'],item['address'],item['ori_url']))
        # self.conn.commit()

    def handle_error(self, error, item, spider):
        print('=^=' * 5, 'error_start:')
        print(error)
        print('=^=' * 5, 'error_end')


middlewares中间件使用selenium替代访问并获取cookie

# 可以写在一个新的中间件中并设置优先级
class CookieSpiderDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.
    # def __init__(self):
	
       def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called

        # 打开并访问网页
        print("request.url:--",request.url)
        driver.get(request.url)
        # 隐式等待
        a = WebDriverWait(driver, 8).until(
            EC.presence_of_element_located(
                (By.XPATH, '//h3[contains(@class,"bili-video-card__info--tit")]')))  # 通过XPATH查找
        if a:
            print("等到了a",a)
            source = driver.page_source
            # print("获取到的类型为",type(source))
            response = HtmlResponse(url=driver.current_url, body=source, request=request, encoding='utf8')
            return response
        else:
            return None

SQl

coon = connect(host='localhost', port=3306, db='boss_zhi_pin',
             user='root', passwd='password', charset='utf8')
cur = coon.cursor()

sql_order = """insert into boss_position_4 (search_word,city_name,position_name ,company_name,areas,street,company_style,scale,
               xue_li,work_experience,financing_situation, benefits,salary,salary_month,
              salary_min,salary_max,average_salary) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
params1 = ['岗位', '城市', '岗位具体名称', '公司名称', '所在区域', '所在街道', '公司类型', '公司规模', '学历要求', '工作经验', '融资情况', '福利待遇', '薪资(K)',
        '发放月数', '最低薪资', '最高薪资', '平均薪资']
cur.execute(sql_order, params1)  # 这里第一次执行是建立字段名(可不写)
coon.commit()

# 关闭连接
cur.close()
coon.close()

ip池子

ip_source = [{"ip": "27.9.47.216", "port": 4220}, {"ip": "183.166.135.43", "port": 4226},
                 {"ip": "101.74.181.221", "port": 4245}, {"ip": "175.147.100.112", "port": 4260},
                 {"ip": "115.205.77.140", "port": 4286}, {"ip": "113.237.4.211", "port": 4256},
                 {"ip": "116.115.209.201", "port": 4245}, {"ip": "175.174.190.95", "port": 4251},
                 {"ip": "106.112.124.153", "port": 4278}, {"ip": "125.79.200.156", "port": 4281}]

到了这里,关于python爬虫selenium+scrapy常用功能笔记的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • python爬虫进阶篇:Scrapy中使用Selenium+Firefox浏览器爬取沪深A股股票行情

    上篇记录了Scrapy搭配selenium的使用方法,有了基本的了解后我们可以将这项技术落实到实际需求中。目前很多股票网站的行情信息都是动态数据,我们可以用Scrapy+selenium对股票进行实时采集并持久化,再进行数据分析、邮件通知等操作。 详情请看上篇笔记 items middlewares setti

    2024年02月04日
    浏览(42)
  • 爬虫框架有Scrapy、BeautifulSoup、Selenium

    爬虫框架有Scrapy、BeautifulSoup、Selenium BeautifulSoup比Scrapy相对容易学习。 Scrapy的扩展,支持和社区比BeautifulSoup更大。 Scrapy应被视为蜘蛛,而BeautifulSoup则是Parser。 1.爬虫基础知识 在开始Python爬虫之前,需要先掌握一些基础知识。首先了解一下HTTP协议,掌握常见的请求方法和状

    2024年02月07日
    浏览(29)
  • 使用Scrapy框架集成Selenium实现高效爬虫

    在网络爬虫的开发中,有时候我们需要处理一些JavaScript动态生成的内容或进行一些复杂的操作,这时候传统的基于请求和响应的爬虫框架就显得力不从心了。为了解决这个问题,我们可以使用Scrapy框架集成Selenium来实现高效的爬虫。 Scrapy是一个使用Python编写的开源网络爬虫框

    2024年02月09日
    浏览(32)
  • Scrapy爬虫框架集成Selenium来解析动态网页

    当前网站普遍采用了javascript 动态页面,特别是vue与react的普及,使用scrapy框架定位动态网页元素十分困难,而selenium是最流行的浏览器自动化工具,可以模拟浏览器来操作网页,解析元素,执行动作,可以处理动态网页,使用selenium处理1个大型网站,速度很慢,而且非常耗资

    2024年02月15日
    浏览(35)
  • 爬虫学习 Scrapy中间件&代理&UA随机&selenium使用

    控制台操作 (百度只起个名 scrapy startproject mid scrapy genspider baidu baidu.com setting.py内 运行 scrapy crawl baidu middlewares.py 中间件 先看下载器中间件 重点在 process_request 在引擎将请求的信息交给下载器之前,自动的调用该方法 process_response… process_exception 异常 (看名就知道了…) spider

    2024年03月23日
    浏览(34)
  • Python爬虫学习笔记(七)————Selenium

    目录 1.什么是selenium? 2.为什么使用selenium? 3.selenium安装 4.selenium的使用步骤 5.selenium的元素定位 6.访问元素信息 7.交互 1.什么是selenium? (1)Selenium是一个用于Web应用程序测试的工具。 (2)Selenium 测试直接运行在浏览器中,就像真正的用户在操作一样。 (3)支持通过各种

    2024年02月16日
    浏览(28)
  • python爬虫教程:selenium常用API用法和浏览器控制

    selenium api selenium 新版本( 4.8.2 )很多函数,包括元素定位、很多 API 方法均发生变化,本文记录以 selenium4.8.2 为准。 webdriver 常用 API 方法 描述 get(String url) 访问目标url地址,打开网页 current_url 获取当前页面url地址 title 获取页面标题 page_source 获取页面源代码 close() 关闭浏览器当

    2024年02月05日
    浏览(38)
  • python爬虫selenium行为链常用方法汇总(1),靠着这份190页的面试资料

    actions.send_keys_to_element(input_elm, ‘侯小啾’) actions.click(button_elm) actions.perform() 常用方法汇总: move_to_element() 将鼠标移动到指定element,参数为标签。 move_by_offset(xoffset, yoffset) 将鼠标移动到与当前鼠标位置的偏移处。参数为X轴Y轴上移动的距离。(距离单位为像素,可以通过截图

    2024年04月13日
    浏览(29)
  • 编程小白的自学笔记十二(python爬虫入门四Selenium的使用实例二)

    编程小白的自学笔记十一(python爬虫入门三Selenium的使用+实例详解) 编程小白的自学笔记十(python爬虫入门二+实例代码详解)  编程小白的自学笔记九(python爬虫入门+代码详解)  目录 系列文章目录 前言 一、使用Selenium打开子页面 二、使用Selenium实现网页滚动 三、使用

    2024年02月15日
    浏览(25)
  • 编程小白的自学笔记十一(python爬虫入门三Selenium的使用+实例详解)

    编程小白的自学笔记十(python爬虫入门二+实例代码详解 编程小白的自学笔记九(python爬虫入门+代码详解)  编程小白的自学笔记八(python中的多线程)  编程小白的自学笔记七(python中类的继承)  目录 系列文章目录 文章目录 前言 一、Selenium是什么 二、安装Selenium  三、

    2024年02月16日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包