class LinkSpider(scrapy.Spider):
name = "link"
def start_requests(self):
urlBasang = "https://bloomberg.com"
yield scrapy.Request(url = urlBasang, callback = self.parse)
def parse(self, response):
newCsv = open('data_information/link.csv', 'a')
for j in response.xpath('//a'):
title_to_save = j.xpath('/text()').extract_first()
href_to_save= j.xpath('/@href').extract_first()
print("test")
print(title_to_save)
print(href_to_save)
newCsv.write(title_to_save+ "\n")
newCsv.close()
这是我代码,但title_to_保存和href_to_save返回None
我想获取标记“a”及其href中的所有文本
1条答案
按热度按时间8yoxcaq71#
你要
注意路径前面的点(由于这个原因,我使用
get
而不是extract_first
)。在输出csv中,您可能已经意识到了,但是您可能应该将您想要写出的信息
yield
,然后使用-o data_information/link.csv
选项运行spider,这比在parse
方法中打开一个文件进行追加要灵活一些。