【问题标题】:Python Scrapy Date Extraction IssuePython Scrapy 日期提取问题
【发布时间】: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


【解决方案1】:

您的脚本中似乎有一个无用的datetime (datetime.datetime.strptime) 您还可以使用正则表达式更改日期格式。与re.sub

data = "01. 01. 2008"
print(re.sub("^(\d+).+?(\d+).+(\d{4})$",'\g<3>-\g<2>-\g<1>',data))

输出:

2008-01-01

关于您的问题,使用len() 生成与网页上显示的匹配数量相同长度的列表:

date = re.sub("^(\d+).+?(\d+).+(\d{4})$",'\g<3>-\g<2>-\g<1>',data)
nbel = len(response.xpath('//table[@class="result"]//a[contains(@href,"match-detail")]').extract
dates = [date]*nbel

输出:

['2008-01-01', '2008-01-01', '2008-01-01',...,'2008-01-01', '2008-01-01', '2008-01-01']

根据您的预期输出,您可以通过这种方式构建您的字典(dates 是包含所有日期的列表,ids 是包含所有 id 的列表,它们具有相同的长度):

dic={}
dic["matches:"]=[]
for el in range(1,len(ids)):
    dic1={"id:":ids[el],"date":dates[el]}
    dic["matches:"].append(dic1)

print(dic)

输出:

{'matches:': [{'id:': '1893063', 'date': '2020-08-04'}, {'id:': '1893067', 'date': '2020-08-04'}, {'id:': '1893062', 'date': '2020-08-04'}, {'id:': '1893059', 'date': '2020-08-04'}, {'id:': '1893061', 'date': '2020-08-04'}, {'id:': '1893066', 'date': '2020-08-04'}, {'id:': '1893229', 'date': '2020-08-04'}, {'id:': '1893065', 'date': '2020-08-04'}, {'id:': '1893117', 'date': '2020-08-04'}, {'id:': '1893134', 'date': '2020-08-04'}, {'id:': '1893133', 'date': '2020-08-04'}, {'id:': '1893130', 'date': '2020-08-04'}, {'id:': '1893158', 'date': '2020-08-04'}, {'id:': '1893048', 'date': '2020-08-04'}, {'id:': '1893047', 'date': '2020-08-04'}, {'id:': '1893045', 'date': '2020-08-04'}, {'id:': '1893046', 'date': '2020-08-04'}, {'id:': '1893109', 'date': '2020-08-04'}, {'id:': '1893110', 'date': '2020-08-04'}, {'id:': '1893107', 'date': '2020-08-04'}, {'id:': '1893108', 'date': '2020-08-04'}, {'id:': '1893105', 'date': '2020-08-04'}, {'id:': '1893106', 'date': '2020-08-04'}, {'id:': '1893058', 'date': '2020-08-04'}, {'id:': '1893057', 'date': '2020-08-04'}, {'id:': '1893056', 'date': '2020-08-04'}, {'id:': '1893055', 'date': '2020-08-04'}, {'id:': '1893054', 'date': '2020-08-04'}, {'id:': '1893053', 'date': '2020-08-04'}, {'id:': '1893139', 'date': '2020-08-04'}, {'id:': '1893131', 'date': '2020-08-04'}, {'id:': '1893102', 'date': '2020-08-04'}, {'id:': '1893116', 'date': '2020-08-04'}, {'id:': '1893115', 'date': '2020-08-04'}, {'id:': '1893114', 'date': '2020-08-04'}, {'id:': '1893113', 'date': '2020-08-04'}]}

视觉输出:

【讨论】:

  • 我收到“dates = [date]*nbel”的无效语法错误
  • 好的,我更新了代码。您可以在此处查看更新的代码:python-forum.io/… 非常感谢您的帮助。真的。
  • 我没有语法错误。您应该指定预期的输出。我用构建字典的解决方案编辑了我的帖子。
猜你喜欢
  • 2020-03-25
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
相关资源
最近更新 更多