会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 134310个问题

import scrapy


class DoubanSpider(scrapy.Spider):
    name = 'douban'
    allowed_domains = ['douban.com']
    start_urls = ['https://movie.douban.com/top250?start=50&filter=']

    def parse(self, response):
        names = response.xpath('//div[@class="hd"]/a/span[1]/text()').getall()
        scores = response.xpath('//span[@class="rating_num"]/text()').extract()

        # 保存数据
        for name,score in zip(names,scores):
            yield {
                'name':name,
                'score':score
            }

老师,我这个为什么生成器生成不了

终端代码是这个

(spider_env) D:\Pycharm开发环境\scrapy04\scrapy04>scrapy crawl douban2 -o douban2.json -t json

D:\Python_env\spider_env\lib\site-packages\scrapy\commands\__init__.py:131: ScrapyDeprecationWarning: The -t command line option is deprecated i

n favor of specifying the output format within the output URI. See the documentation of the -o and -O options for more information.

  feeds = feed_process_params_from_cli(

D:\Python_env\spider_env\lib\site-packages\scrapy\spiderloader.py:37: UserWarning: There are several spiders with the same name:


  DoubanSpider named 'douban' (in scrapy04.spiders.douban)


  DoubanSpider named 'douban' (in scrapy04.spiders.douban2)


  This can cause unexpected behavior.

  warnings.warn(

2022-09-23 10:17:11 [scrapy.utils.log] INFO: Scrapy 2.6.2 started (bot: scrapy04)

2022-09-23 10:17:11 [scrapy.utils.log] INFO: Versions: lxml 4.9.1.0, libxml2 2.9.12, cssselect 1.1.0, parsel 1.6.0, w3lib 2.0.1, Twisted 22.8.0,

 Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)], pyOpenSSL 22.0.0 (OpenSSL 3.0.5 5 Jul 2022), cryptograph

y 38.0.1, Platform Windows-10-10.0.22000-SP0

Traceback (most recent call last):

  File "D:\Python_env\spider_env\lib\site-packages\scrapy\spiderloader.py", line 75, in load

    return self._spiders[spider_name]

KeyError: 'douban2'


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

  File "D:\Program Files\Python39\lib\runpy.py", line 197, in _run_module_as_main

    return _run_code(code, main_globals, None,

  File "D:\Program Files\Python39\lib\runpy.py", line 87, in _run_code

    exec(code, run_globals)

  File "D:\Python_env\spider_env\Scripts\scrapy.exe\__main__.py", line 7, in <module>

  File "D:\Python_env\spider_env\lib\site-packages\scrapy\cmdline.py", line 154, in execute

    _run_print_help(parser, _run_command, cmd, args, opts)

  File "D:\Python_env\spider_env\lib\site-packages\scrapy\cmdline.py", line 109, in _run_print_help

    func(*a, **kw)

  File "D:\Python_env\spider_env\lib\site-packages\scrapy\cmdline.py", line 162, in _run_command

    cmd.run(args, opts)

  File "D:\Python_env\spider_env\lib\site-packages\scrapy\commands\crawl.py", line 22, in run

    crawl_defer = self.crawler_process.crawl(spname, **opts.spargs)

  File "D:\Python_env\spider_env\lib\site-packages\scrapy\crawler.py", line 204, in crawl

    crawler = self.create_crawler(crawler_or_spidercls)

  File "D:\Python_env\spider_env\lib\site-packages\scrapy\crawler.py", line 237, in create_crawler

    return self._create_crawler(crawler_or_spidercls)

  File "D:\Python_env\spider_env\lib\site-packages\scrapy\crawler.py", line 312, in _create_crawler

    spidercls = self.spider_loader.load(spidercls)

  File "D:\Python_env\spider_env\lib\site-packages\scrapy\spiderloader.py", line 77, in load

    raise KeyError(f"Spider not found: {spider_name}")

KeyError: 'Spider not found: douban2'


Python全系列/第十六阶段:Python 爬虫开发/scrapy框架使用 226楼
Python全系列/第十六阶段:Python 爬虫开发/爬虫反反爬- 228楼

from time import sleep  # 导入sleep模块,用于控制程序休眠
from selenium.webdriver import Edge, EdgeOptions  # 导入Edge和EdgeOptions类,用于创建Edge浏览器驱动
from selenium.webdriver.common.by import By  # 导入By类,用于定义定位元素的方式
from lxml import etree  # 导入etree模块,用于解析HTML源码


def huya():  # 定义一个名为huya的函数
    options = EdgeOptions()  # 创建一个EdgeOptions对象
    edge = Edge(options=options)  # 使用EdgeOptions对象创建一个Edge浏览器实例
    # 向浏览器发送命令,向新文档添加一个脚本
    edge.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
         Object.defineProperty(navigator, 'webdriver', {
         get: () => false
         })
       """
    })
    edge.get("https://www.huya.com/g/lol")  # 打开指定网页
    edge.implicitly_wait(10)  # 设置隐式等待时间为10秒
    edge.switch_to.frame('UDBSdkLgn_iframe')  # 切换到名称为'UDBSdkLgn_iframe'的iframe框架
    # 定位id为'close-udbLogin'的元素,并点击
    edge.find_element(By.ID, 'close-udbLogin').click()
    count = 1  # 初始化计数器为1
    while True:  # 进入循环,直到条件不满足为止
        sleep(1)  # 休眠1秒
        e = etree.HTML(edge.page_source)  # 将浏览器页面源码解析为HTML对象
        names = e.xpath('//a[@class="title"]/text()')  # 使用xpath定位方式获取所有a标签中class为"title"的文本内容
        persons = e.xpath('//i[@class="nick"]/text()')  # 使用xpath定位方式获取所有i标签中class为"nick"的文本内容
        hots = e.xpath('//i[@class="js-num"]/text()')  # 使用xpath定位方式获取所有i标签中class为"js-num"的文本内容
        for name, person, hot in zip(names, persons, hots):  # 遍历name、person和hot列表
            print(f'直播间:{name},主播:{person},热度:{hot}')  # 打印直播间名称、主播和热度信息
        print(f'第{count}页')  # 打印当前页码
        count += 1  # 计数器加1
        try:
            next_btn = edge.find_element(By.XPATH, '//a[@class="laypage_next"]')  # 定位class为"laypage_next"的元素
            next_btn.click()  # 点击定位到的元素
        except Exception as e:  # 如果发生异常,捕获异常信息并命名为e
            break  # 跳出循环

    edge.quit()  # 关闭浏览器


if __name__ == '__main__':  # 如果程序作为主程序运行
    huya()  # 调用huya函数

while True下面那个sleep不写的话就太快了导致点不到下一页,但隐式等待没起到作用吗?

Python全系列/第十六阶段:Python 爬虫开发/爬虫基础 229楼
Python全系列/第十六阶段:Python 爬虫开发/scrapy框架使用(旧) 230楼
Python全系列/第十六阶段:Python 爬虫开发/爬虫基础 232楼
Python全系列/第十六阶段:Python 爬虫开发/爬虫基础(旧) 233楼

屏幕截图 2022-04-06 181732.png


Python全系列/第十六阶段:Python 爬虫开发/爬虫基础(旧) 234楼
Python全系列/第十六阶段:Python 爬虫开发/爬虫基础(旧) 236楼

from urllib.request import Request,build_opener
from fake_useragent import UserAgent
from urllib.parse import urlencode
from urllib.request import HTTPCookieProcessor
from http.cookiejar import MozillaCookieJar
def get_cookie():
    login_url = 'https://www.docin.com/app/login'
    # 设置账号密码
    form_data = {
        'user': '18310640655',
        'password': '199759guo'
    }
    # 设置请求头
    headers = {"User-Agent": UserAgent().random}
    # 封装函数
    req = Request(login_url, headers=headers, data=urlencode(form_data).encode())
    #自己保存cookie
    cookie_jar =MozillaCookieJar()
    # 保存cookie
    handler = HTTPCookieProcessor(cookie_jar)
    opener = build_opener(handler)
    resp = opener.open(req)
    #无论我的cookie是否过期都将保存下来
    cookie_jar.save('cookie.txt',ignore_discard=True,ignore_expires=True)

def use_cookie():
    info_url = 'https://www.docin.com/'
    headers = {'User-Agent':UserAgent().random}
    req = Request(info_url,headers=headers)

    #加载cookie信息
    cookie_jar = MozillaCookieJar()
    cookie_jar.load('cookie.txt',ignore_discard=True,ignore_expires=True)
    handler = HTTPCookieProcessor(cookie_jar)
    #将信息放到控制器里面
    opener = build_opener(handler)
    resp = opener.open(req)

    print(resp.read().decode())

if __name__ == '__main__':
    get_cookie()
    use_cookie()

image.png


老师,我尝试用cookie登录豆丁网,为什么我保存下来的cookie信息是这样的。并且无法登录

Python全系列/第十六阶段:Python 爬虫开发/scrapy框架使用(旧) 240楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637