python - 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
这是一个值
这是一个值
这是一个值
我究竟做错了什么?
解决方案
您的第一个打印输出href
s列表
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()
推荐阅读
- regex - 这些字符串的正则表达式
- html - 隐藏元素仍在下拉导航中占用空间
- javascript - 如何合并和汇总来自 MongoDB 的结果
- c# - 如何在类中初始化不可为空的字符串?
- java - 什么是 JSON 等价于 @XmlAnyElement?
- hive - 如何在 Hive 中重新加载更新的自定义 UDF 函数?
- python - 如何将本地 .sql 文件导入 pythonanywhere 数据库?
- algorithm - 复杂算法:如何从数据中重构 OR 规则
- python - 在heroku上启动时无法将邮件合并到模板word文档中
- excel - Dynamic data structures in VBA