首页 > 解决方案 > Python/scrapy 嵌套的 for/if 循环工作不正确

问题描述

我正在使用 scrapy 从 www.tf2items.com/profiles/ 抓取用户列表及其 SteamID。

目前,我的代码如下所示:

import scrapy

bot_words = [
"bot",
"BOT",
"[tf2mart]"
]

class AccountSpider(scrapy.Spider):
    name = "accounts"
    start_urls = [  
'file:///Users/max/Documents/promotebot/tutorial/tutorial/TF2ITEMS.htm'
    ]

def parse(self, response):
    for tr in response.css("tbody"):
        user = response.css("span a").extract()
        print(user)
        if bot_words not in response.css("span a").extract():
            for href in response.css("span a::attr(href)").extract():
                #yield response.follow("http://www.backpack.tf" + href, self.parse_accounts)
                print("this is a value")

我的最终目标是让这段代码打印出如下内容:

a href="/profiles/76561198042757507">Kchypark

这是一个值

a href="/profiles/76561198049853548">Agen Kolar

这是一个值

a href="/profiles/76561198036381323">Grave Shifter15

这是一个值

有了这个当前的代码,我什至可以期待

a href="/profiles/76561198042757507">Kchypark

这是一个值

这是一个值

这是一个值

a href="/profiles/76561198049853548">Agen Kolar

这是一个值

这是一个值

这是一个值

a href="/profiles/76561198036381323">Grave Shifter15

这是一个值

这是一个值

这是一个值

但是,我得到:

a href="/profiles/76561198042757507">Kchypark

a href="/profiles/76561198049853548">Agen Kolar

a href="/profiles/76561198036381323">Grave Shifter15

这是一个值

这是一个值

这是一个值

我究竟做错了什么?

标签: pythonpython-3.xfor-loopscrapyscrapy-spider

解决方案


您的第一个打印输出hrefs列表

user = response.css("span a").extract()
print(user)

你的代码应该看起来像

def parse(self, response):
    for tr in response.css("tbody"):
        for user in response.css("span a"):
            if bot_words not in user:
                print(user.extract())
                href = user.css('::attr(href)').extract()[0]
                print(href)
                #yield response.follow("http://www.backpack.tf" + href, self.parse_accounts)
                print("this is a value")

此外,srapy 的最佳实践是使用项目而不是原始print函数。

并注意代码重复,例如response.css("span a").extract()


推荐阅读