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_save和href_to_save返回None
我想获取标记“ a”及其href内的所有文本
答案 0 :(得分:1)
您想要
title_to_save = j.xpath('./text()').get()
href_to_save= j.xpath('./@href').get()
注意路径前面的点
(由于this,我使用get
代替了extract_first
)。
在输出csv上,您可能已经知道了,但是您可能应该yield
要写出的信息,然后使用-o data_information/link.csv
选项运行Spider,它比打开a文件添加到您的parse
方法中。因此您的代码看起来像
class LinkSpider(scrapy.Spider):
name = "link"
# No need for start_requests for as this is the default anyway
start_urls = ["https://bloomberg.com"]
def parse(self, response):
for j in response.xpath('//a'):
title_to_save = j.xpath('./text()').get()
href_to_save= j.xpath('./@href').get()
print("test")
print(title_to_save)
print(href_to_save)
yield {'title': title_to_save}