python - Scrapy 不能同时使用 return 和yield

标签 python scrapy

这是我的代码

def parse(self, response):
    soup = BeautifulSoup(response.body)
    hxs = HtmlXPathSelector(response)
    sites = hxs.select('//div[@class="row"]')
    items = []

    for site in sites[:5]:
        item = TestItem()
        item['username'] = "test5"
        request =  Request("http://www.example.org/profile.php",  callback = self.parseUserProfile)
        request.meta['item'] = item
        **yield item**

    mylinks= soup.find_all("a", text="Next")
    if mylinks:
        nextlink = mylinks[0].get('href')
        yield Request(urljoin(response.url, nextlink), callback=self.parse)

def parseUserProfile(self, response):
    item = response.meta['item']
    item['image_urls'] = "test3"
    return item

现在我的上述内容可以工作,但我没有获得 item['image_urls'] = "test3"

的值

它为空

现在如果使用返回请求而不是yield item

然后出现错误,无法将 return 与生成器一起使用

如果我删除这一行

yield 请求(urljoin(response.url, nextlink),callback=self.parse) 然后我的代码工作正常,我可以得到 image_urls 但我无法点击链接

有什么办法让我可以使用返回请求一起产生以便我获得item_urls

最佳答案

我不太明白你的问题,但我在你的代码中发现一个问题:

def parseUserProfile(self, response):
    item = response.meta['item']
    item['image_urls'] = "test3"
    return item

解析回调返回值应该是序列,因此您应该return [item]或将回调转换为生成器:

def parseUserProfile(self, response):
    item = response.meta['item']
    item['image_urls'] = "test3"
    yield item

关于python - Scrapy 不能同时使用 return 和yield,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13900877/

相关文章:

python - Scrapy:LinkExtractor 不工作

Python 3.3 解释器和一行问题(4 行语句工作正常......)

python - Python 3.5 中的 JSON 错误

python - Flask:开发中如何实现媒体 Assets 的动态路由?

python - Scrapy中如何获取上层函数的url地址?

python - Scrapy - 使用 JOBDIR 获取重复项

python - 多变量线性回归 - Python - 实现问题

python - Pydantic 数据转换和 PyCharm 的 PyTypeChecker

parsing - Scrapy:将列表项解析到单独的行上

python - Scrapy LinkExtractor 无法找到现有的 url