【发布时间】:2020-08-05 00:44:39
【问题描述】:
我正在努力解决如何使用 Python Scrapy 正确提取页面上某个位置存在的格式奇怪的日期。
需要进行哪些更改才能以 yyyy-mm-dd 格式将日期包含在每个输出行中?
有问题的代码行:
data2 = response.xpath('//span[@class="tab"]/text()').get().replace(". ", "-")
date = datetime.datetime.strptime(data2, "%d-%m-%Y").strftime("%Y-%m-%d")
示例输出似乎包含一个日期字符。 示例:{'match_id': '1893065', 'date': '0'}
这是完整的蜘蛛。
导入scrapy 导入日期时间 重新进口 从日期时间导入时间增量
class Tennis_ExplorerSpider(scrapy.Spider):
name = 'tennis_explorer'
allowed_domains = ['tennisexplorer.com']
def daterange(start_date, end_date):
for n in range(int((end_date - start_date).days)):
yield start_date + timedelta(n)
start_date = datetime.datetime.today() - datetime.timedelta(days=1)
end_date = datetime.datetime.today() + datetime.timedelta(days=1)
start_urls = []
start_url='https://www.tennisexplorer.com/matches/?type=all&year='
for single_date in daterange(start_date, end_date):
start_urls.append(single_date.strftime(start_url+"%Y&month=%m&day=%d&timezone=-6"))
def parse(self, response):
#Extracting the content using xpath
self.logger.debug('callback "parse": got response %r' % response)
data = response.xpath('//table[@class="result"]//a[contains(@href,"match-detail")]/@href').extract()
match_id =[re.sub('^.+=','',el) for el in data]
data2 = response.xpath('//span[@class="tab"]/text()').get().replace(". ", "-")
date = datetime.datetime.strptime(data2, "%d-%m-%Y").strftime("%Y-%m-%d")
#Give the extracted content row wise
for item in zip(match_id, date):
#create a dictionary to store the scraped info
scraped_info = {
'match_id' : item[0],
'date' : item[1]
}
#yield or give the scraped info to scrapy
yield scraped_info
【问题讨论】:
-
只有部分日期的格式与您的预期不同?
-
@AMC 输出中只显示一个字符。没有日期格式正确。
-
对,是的,我把它和
match_id混淆了。您是否进行了任何调试以缩小问题范围? -
你可能对
zip(match_id, date)有问题,因为match_id是一个ID 列表,但date是单个字符串,而不是日期列表。但是 Python 将字符串视为字符列表,zip()从该列表中获取单个字符。您不应该为此使用zip(),而是正常使用for match in match_id: scraped_info = { 'match_id' : match, 'date' : data}。或者scraped_info = { 'match_id' : match_id[0], 'date' : data}没有for-loop,当您只需要一个结果时。
标签: python python-3.x xpath web-scraping scrapy