好头发用飘影 2022-10-17 22:06 采纳率: 0%
浏览 7
已结题

使用python scrapy+ selenium时,用yield item 提交出现错误

使用python scrapy+ selenium时,用yield item 提交出现错误
这是爬虫文件
import scrapy
from selenium import webdriver
from  selenium.webdriver.chrome.options import Options    # 使用无头浏览器
from selenium.webdriver import ActionChains
import time
# from scrapy.http import HtmlResponse
from weiqi.items import FileItem


chorme_options = Options()
chorme_options.add_argument("--headless")
chorme_options.add_argument("--disable-gpu")

# 检查元素是否存在
def check_element_exists(driver, element, condition):
    try:
        if condition == 'class':
            driver.find_element_by_class_name(element)
        elif condition == 'id':
            driver.find_element_by_id(element)
        elif condition == 'xpath':
            driver.find_element_by_xpath(element)
        return True
    except Exception as e:
        return False

class Number1Spider(scrapy.Spider):
    name = 'number2'
    # allowed_domains = ['www.asxs.net']
    start_urls = ['https://www.101weiqi.com/newbook/#/book/42983/']
    
    def __init__(self):
            self.bro = webdriver.Chrome()
            super().__init__()

    def parse(self, response):
        print(response)
        url='https://www.101weiqi.com/newbook/#/book/42983/'
        yield scrapy.Request(url,callback=self.parse_page,meta={'is_bro':True})
        pass

    def parse_page(self,response):
        
        #点击进入题目列表页
        self.element_click('//*[@id="root"]/div/div[2]/div/div/div/div[1]')
        time.sleep(3)
        #获取图片地址
        print('get_img')
        self.get_img_urls(response)
        
    #通过xpath获取元素并单击
    def element_click(self,xpath):
        soutu_btn = self.bro.find_element_by_xpath(xpath)  # 将需要单击的WebElement对象定义为day
        actions = ActionChains(self.bro)  # 实例化Actions类对象: actions, 并将driver传给actions
        actions.move_to_element(soutu_btn).click().perform()
    
    def get_img_urls(self,response):
        print('geting_imgsrc')
        img_url =self.bro.find_elements_by_xpath('//div[@class="sc-gGCDDS tzeuw"]//img')
        path_name = self.bro.find_elements_by_xpath('//*[@id="root"]/div/div[2]/div/div[1]/div[1]/span[3]')[0].text
        
        file_urls = []
        file_names = []
        for link in img_url:
            file_urls.append(link.get_attribute('src'))
            file_names.append(link.get_attribute('src').split('/')[-1])
            
        item = FileItem()
        
        item['file_names'] = file_names
        item['file_urls'] = file_urls
          #这里,只要用yield item ,就会导致整个函数不再运行。
          #如果只是print 出来,是没有问题的
        yield item      
        
    def closed(self,spider):
        print('关闭浏览器对象!')
        self.bro.quit()

最后使用yield 提交item的时候,会导致整个get_img_urls函数不运行。

我尝试过将yield item 单独写一个函数,则只要有yield item的函数就不运行。换成print(item)则可以正常打印出来。
下面是同一个工程下的另一个爬虫,yield item 没有问题。

import scrapy
from selenium import webdriver
from weiqi.items import FileItem
from  selenium.webdriver.chrome.options import Options    # 使用无头浏览器

chorme_options = Options()
chorme_options.add_argument("--headless")
chorme_options.add_argument("--disable-gpu")


class Number1Spider(scrapy.Spider):
    name = 'number1'
    # allowed_domains = ['www.asxs.net']
    start_urls = ['https://www.101weiqi.com/newbook/#/chapter/53608/']

    def __init__(self):
            self.bro = webdriver.Chrome()
            super().__init__()

    #获取索引页内容
    def parse(self, response):       

        imgs = response.xpath('//div[@class="sc-gGCDDS tzeuw"]//img/@src').extract()
        imgname = []
        for imgurl in imgs: 
            imgname.append(imgurl.split('/')[-1])
        print(imgname)
            
        item = FileItem()
        item['file_urls'] = imgs
        item['file_names'] = imgname
        print(item)
        yield item


    def closed(self,spider):
        print('关闭浏览器对象!')
        self.bro.quit()

实在找不到原因,请各位朋友帮忙!

  • 写回答

1条回答 默认 最新

  • 好头发用飘影 2022-10-17 23:11
    关注

    自己改了下,把item放到了parse函数中去yield。
    获取过程写成函数,然后把item传回parse中。
    这样就可以正常提交了。

    不知道为什么?是因为除了parse函数外,其他函数无法提交item吗?

    评论

报告相同问题?

问题事件

  • 系统已结题 10月25日
  • 修改了问题 10月17日
  • 创建了问题 10月17日

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图