Python/scrapy 嵌套 for/if 循环工作不正常

Python/scrapy nested for/if loop working incorrectly

我正在使用 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

this is a value

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

this is a value

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

this is a value

使用当前代码,我什至可以期待

a href="/profiles/76561198042757507">Kchypark

this is a value

this is a value

this is a value

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

this is a value

this is a value

this is a value

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

this is a value

this is a value

this is a value

但是,我得到:

a href="/profiles/76561198042757507">Kchypark

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

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

this is a value

this is a value

this is a value

我做错了什么?

你的第一个打印输出 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 中的最佳实践是使用 items 而不是原始 print 函数。

并注意像 response.css("span a").extract()

这样的代码重复